
Real Interview Questions for the Data Engineer at Allegro
NewInterview Q&A
Q&A-1Design chat on an e-commerce page between buyers and sellers?
Reported in What to Expect in the Allegro System Design Interview
The 90-second answer
I would build chat as an append-only event stream, with serving and analytics on separate consumers. The client holds a WebSocket to a gateway, the gateway publishes to Kafka, and one consumer writes the serving store while another feeds the warehouse. That separation is the main decision: a slow Spark job or a backfill must never delay a message reaching the other party.
I would state my assumptions first. Text only at launch, attachments as links to object storage, one conversation per buyer, seller and listing, and users authenticated by the existing account service. Retention is 24 months for active conversations, with soft delete for erasure requests.
Write path and storage
Client --WebSocket--> Gateway --publish--> Kafka chat.messages
|---> Stream processor --> Cassandra (serving)
|---> Moderation consumer --> flag topic
+---> Spark Structured Streaming --> Bronze/Silver
Cassandra --> Gateway --> Client (history fetch)The serving table is keyed for the timeline view:
| Field | Notes |
|---|---|
conversation_id | Partition key, one per buyer, seller, listing |
sent_at | Clustering key, server time |
message_id | UUID v7 generated by the client, clustering key |
sender_id, listing_id | Dimensions for inbox and analytics |
body, event_type | Text, system, or order event |
deleted_at | Set by the GDPR erasure job |
In the warehouse I land the raw Kafka topic in bronze, then build silver partitioned by date(sent_at) and clustered by conversation_id. That keeps the common query, messages per seller per day, from scanning all history. Presence and typing indicators go only to Redis with a 30 second TTL. They are never persisted, which avoids multiplying event volume for data nobody queries.
Duplicates, ordering, and sizing
Clients retry after timeouts, so delivery is at-least-once. I would not claim exactly-once. The processor checks a separate dedupe table keyed by message_id alone, with a 7 day TTL, before inserting into the timeline table. That check has to be separate because message_id is not the partition key of the timeline table, so an upsert there cannot collapse a duplicate on its own. If the id is already present, the processor skips the write and the gateway can return the original timestamp. The effect is idempotent even though delivery is not exactly-once.
Kafka is partitioned by hash of conversation_id, 60 partitions in my sizing below, so ordering holds inside a conversation and one hot seller does not stall others.
Hypothetical sizing, labelled as such: 2 million messages per day at peak, 700 bytes per message including metadata. That is 1.4 GB per day raw, 4.2 GB per day with replication factor 3, and about 29 GB across the cluster for 7 days of Kafka retention. A flash sale at 10 million messages per day moves the bottleneck to gateway connections, roughly 80,000 concurrent WebSockets, before it moves to storage.
Failure modes
A poison message, oversized body or invalid UTF-8, blocks its partition. The processor retries 3 times, then sends it to a dead letter topic and alerts if dead letters exceed 0.1% of throughput. Consumer lag in the Spark job shows up as bronze delay, monitored as now() - max(sent_at) per partition, while serving keeps working from Cassandra. Erasure is a nightly job that sets deleted_at in Cassandra and publishes a tombstone event so silver and the search index drop the body within 24 hours. If a gateway node dies, the client reconnects elsewhere and fetches missed messages with a sent_at cursor, not an offset, so reconnects do not skip or repeat a page.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-2Design the path from a seller publishing an offer to a buyer finding it?
Reported in What to Expect in the Allegro System Design Interview
The 90-second answer
I would split this into a write path the seller controls and a read path the buyer controls, joined by an event stream. The seller's publish call commits once to the transactional store. Everything downstream, search index, catalog cache, analytics, recommendations, is built from change events off that commit. The buyer never reads the transactional store. They read a denormalized index that is optimized for search and filtering.
That split is the whole design. It gives us a single source of truth for correctness and a separate system we can scale, tune and rebuild for discovery.
Seller publish API
|
v
[Offer service] --tx--> [Postgres: offers, offer_items, prices]
| |
| outbox table | CDC (Debezium)
+-------------------------+
v
Kafka: offer.changed.v1
|
+-----------------+-----------------+
v v v
[Stream validation [Enrichment [Warehouse
+ dedup + schema join: category, loader]
checks] seller, stock,
| geo, price]
v |
[Search indexer] <------+
|
v
[OpenSearch index: offer_id, title, category,
price, stock, seller_rating, delivery, geo]
|
Buyer search API --> query, filters, ranking --> resultsWhat happens on publish, step by step
- The offer service validates the seller owns the product, price and stock are in range, and category attributes required for that category are present. It writes the offer row and an outbox row in the same transaction. The API returns
202with the offer id. It does not wait for search indexing. - Debezium captures the outbox or the offer table change and publishes
offer.changed.v1withoffer_id,version,event_typeandoccurred_at. Kafka is partitioned byoffer_id, so updates for one offer stay ordered. - A stream job validates the schema against a registry, drops duplicates by
(offer_id, version), and enriches the event. Enrichment joins category taxonomy, seller rating and trust signals, current stock, and delivery options. This is where most data engineering work lives, because the search document needs fields the transactional model does not store together. - The indexer upserts the document into OpenSearch. A separate loader writes the same enriched record to the warehouse for analytics and to a feature store for ranking.
Worked trace, hypothetical figures for a peak hour:
14:00:00.120 POST /offers seller=9918, sku=PL-8841, price=249.00 PLN
14:00:00.180 tx commits: offers.version=7, outbox.id=552910
14:00:00.410 Kafka: offer.changed.v1 key=offer_77120 offset=881204
14:00:01.050 enrichment joins stock=14, category=electronics/phones, rating=4.8
14:00:01.300 OpenSearch upsert acknowledged, doc version=7
14:00:01.900 buyer query "iphone 15" returns offer_77120, rank 3End to end lag in that trace is about 1.8 seconds. I would budget p95 under 5 seconds for index visibility and alert if consumer lag on offer.changed.v1 exceeds 60 seconds, because that is the point where sellers complain the offer is live but buyers cannot find it.
Why the buyer side is a different system
| Concern | Transactional store | Search index |
|---|---|---|
| --- | --- | --- |
| Query pattern | Point lookup by id | Full text, filters, facets, geo |
| Shape | Normalized, many tables | One denormalized document per offer |
| Consistency | Strong, immediate | Eventual, seconds behind |
| Rebuild | Not feasible | Full reindex from warehouse snapshot |
Search needs tokenized title, category path, price bucket, availability and delivery promise in one document. Joining five tables per query at Allegro scale would be slow and would couple buyer traffic to seller writes. The index also lets ranking use offline signals, such as click and purchase history aggregated in the warehouse, without touching the offer service.
Failure modes I would name in the interview
Duplicate delivery: Kafka and Debezium are at-least-once. The indexer must be idempotent on (offer_id, version) and ignore a version lower than the one already indexed. Out-of-order events are handled the same way, plus partition by offer_id.
Stale stock or price: a stock decrement after publish emits another offer.changed.v1. If that event is delayed, the buyer sees an offer they cannot buy. I would put stock and price on a faster path, or have the buyer detail page recheck live stock from the offer service before checkout, and accept that search results can be briefly stale.
Poison pill: an offer with a malformed category attribute fails enrichment repeatedly. Send it to a dead letter topic after a few retries, keep the raw event, and alert with offer_id and schema version. Do not block the partition.
Schema change: add fields as optional first, deploy consumers that tolerate missing fields, then make the producer emit them. Breaking a field rename in offer.changed.v1 without that order breaks every consumer at once.
Index rebuild: if the mapping changes, I would build a new index from a warehouse snapshot, replay Kafka from a retained offset, alias the new index, then drop the old one. That is only possible because the enriched record is also in the warehouse, not only in the search index.
The trade-off I would state plainly: the seller gets a fast, reliable publish, the buyer gets a fast search, and we pay for it with eventual consistency of a few seconds and a pipeline that must be monitored like a product, not a batch job.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-3Design an order flow where a payment is charged once, even when the same request is retried?
Reported in What to Expect in the Allegro System Design Interview
The 90-second answer
I would make the client supply an idempotency key on order creation, persist that key in the same database transaction that creates the order, and pass the same key to the payment provider as its own idempotency key. A retry then cannot create a second order or a second charge. It either finds the completed work and replays the stored response, or finds work in progress and returns the current status.
The core rule is that the database, not a cache or a message queue, is the source of truth for deduplication. Kafka and other streams deliver at least once, so every consumer downstream has to tolerate duplicates too.
Flow
Client --POST /orders, Idempotency-Key: k--> Order API
Order API --INSERT order + idempotency_record(k) in one txn--> DB
Order API --charge(payment_idempotency_key=k)--> Payment Gateway
Payment Gateway --webhook / poll--> Order API --UPDATE order PAID--> DB
DB --transactional outbox--> Kafka (order.paid) --> Warehouse / Fraud / FulfilmentThe outbox matters for a data engineer. If I write the order row and publish to Kafka in separate steps, a crash between them leaves the warehouse missing a paid order or seeing it twice. Writing the event to an outbox table in the same transaction as the order, then publishing it asynchronously, gives at-least-once delivery with a stable event id that downstream jobs can deduplicate on.
Handling the retry
-- orders table has UNIQUE(idempotency_key)
INSERT INTO orders (id, idempotency_key, customer_id, total, status)
VALUES (:order_id, :key, :customer_id, :total, 'PENDING')
ON CONFLICT (idempotency_key) DO NOTHING
RETURNING id;
-- If nothing returned, SELECT the existing row by key and return it.Trace with a real retry:
POST /orderswith key7f3carrives. Insert succeeds, order 42 isPENDING. The API calls the gateway with key7f3cand gets chargech_991.- The response is lost on the network. The client retries with the same key after 2 seconds.
- The insert conflicts on
idempotency_key. The API loads order 42 and returns201with the same body andLocation: /orders/42. No second gateway call is made. - If the retry arrives while the first charge is still in flight, the API returns
202withstatus: PENDINGand aRetry-Afterhint, rather than starting a second charge.
The gateway call itself needs the same protection. Stripe, Adyen and most providers accept an idempotency key and return the original charge for a repeated key, typically for 24 hours. I would store the gateway charge id on the order row before marking it paid, so a webhook arriving twice updates the same row idempotently.
State machine and failure modes
| State | Meaning | Retry behaviour |
|---|---|---|
PENDING | Order saved, charge not confirmed | Return 202, do not charge again |
PAID | Gateway confirmed charge ch_991 | Replay stored 201 response |
FAILED | Gateway declined or timed out | Return stored failure, new attempt needs a new key |
REFUNDED | Charge reversed | Replay original response, refund is a separate resource |
Three failures I would call out in the interview:
- Key reuse with a different payload. Same key, different cart total. The API must compare a request hash stored with the key and return
422on mismatch, otherwise a buggy client silently gets the wrong order. - Crash after charge, before DB update. The gateway has the money, the order still says
PENDING. Reconciliation runs on the gateway webhook and on a periodic poll ofPENDINGorders older than 5 minutes, keyed by the same idempotency key. - Key expiry. Keys are kept for at least 24 hours, longer than any client retry window. After expiry a retry is treated as a new order, which is acceptable because no client retries after a day.
For Allegro scale, say 20,000 orders per minute at peak, the deduplication check is a single indexed insert on idempotency_key, so it adds no extra hop. The expensive part is the gateway call, and that is exactly the call the key suppresses on retry.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-4Design the service that promises a delivery date to a buyer and then keeps that promise accurate?
Reported in What to Expect in the Allegro System Design Interview
The 90-second answer
I would split this into a promise path and a learning path. The promise path answers in under 100 ms at checkout: given seller, warehouse, destination postal code, basket contents and order time, return a date. The learning path watches what actually happened, compares it with the promise, and recalibrates the model per lane. If those two drift apart, the date shown to the buyer becomes fiction.
Assumptions I would state up front: Allegro is a marketplace, so the seller may ship from their own warehouse or from an Allegro fulfilment centre, and the last mile carrier varies by destination. I need a cut-off time per seller and warehouse, a transit time distribution per origin-destination pair and carrier, and a handling time distribution for picking and packing. The promise is a date, not a timestamp, so I optimise for the right calendar day.
promise path (online, p99 < 100 ms)
checkout -> ETA API -> online feature store -> model / rules -> date + confidence
learning path (streaming + batch)
order, payment, warehouse scans, carrier scans, delivery
-> Kafka (raw events, bronze)
-> Flink stream jobs (silver, deduped, late data handled)
-> Hive / Iceberg (gold, one row per order leg)
-> nightly training + calibration -> model registry -> online storeHow the promise is computed
For each order I build features at checkout: origin warehouse or seller location, destination postal code and city, carrier offered, number of items and whether they split across warehouses, order time against the seller cut-off, weekday and public holidays in Poland, and current backlog at the origin warehouse.
The model predicts a distribution of delivery day offset, not a single number. I use quantile regression, for example LightGBM with pinball loss, trained on historical legs. At serving time I pick a quantile based on the business target. If we promise at P50, half the orders will be late. At P85, roughly 15% will be late, but the date looks worse and conversion drops. I would start at P80 to P85 for standard delivery and tune it per category, because a customer buying a fridge tolerates a wider window than a customer buying a phone case.
A deterministic fallback sits underneath the model. If the model has no history for a lane, for example a new seller in Gdansk shipping to a small town, I fall back to carrier-level transit times plus a buffer derived from distance bands. The fallback is explicit in code so an on-call engineer can explain any date without opening a model artefact.
Worked trace, hypothetical figures: order placed Tuesday 14:20 in Warsaw, seller cut-off 16:00, so it ships Tuesday. Warsaw to Krakow via carrier A has median transit 1 day, P85 2 days. Picking adds 0 days at P85 because the warehouse backlog is under 4 hours. Promise = Thursday. If the same order lands at 16:40, after cut-off, dispatch moves to Wednesday and the promise moves to Friday. That single cut-off rule explains a large share of misses in marketplace data, which is why I would log the cut-off version used for every promise.
Keeping it accurate
Every promise is written to a table with the model version, quantile, feature snapshot and cut-off version. When the delivery scan arrives, a join produces the actual offset. I then track calibration per lane, carrier and weekday: promised P85 should be met about 85% of the time. A lane that is at 70% is miscalibrated and gets its buffer widened automatically until the next retrain.
| Signal | Cadence | Action |
|---|---|---|
| Calibration per lane | hourly, streaming | widen buffer if hit rate drops 5 points below target |
| Carrier feed delay | streaming, watermark 6 h | mark affected legs as pending, exclude from training until scans arrive |
| Warehouse backlog spike | streaming | add handling days for new promises from that warehouse |
| Full retrain | nightly batch | new model version, shadow scored for 24 h before serving |
Late and duplicate scans are the main data problem. Carrier feeds resend scans and sometimes deliver them a day late. I dedupe on carrier scan ID in the silver layer, keep event time separate from ingestion time, and use a 6 hour watermark in Flink. Anything later than that still lands in bronze and is picked up by the nightly batch, so training data is complete even if the streaming view is temporarily behind. Backfills replay from bronze, never from the silver tables, so a bug in a stream job does not corrupt history.
Failure modes I would name in the loop
Seller misses their dispatch SLA. The promise assumed Tuesday dispatch, the seller ships Thursday. Detection: dispatch scan timestamp versus promised dispatch date, reported per seller. Response: the ETA API re-promises automatically once the parcel is scanned, and the seller's future promises get a longer handling buffer.
Carrier outage or weather disruption on a corridor. Detection: scan volume for a hub drops to near zero while orders keep flowing. Response: a manual override table per lane that the logistics team can set, with an expiry, so the model does not need a retrain to react.
Address quality. A postal code that geocodes to the wrong depot produces a systematically wrong lane. Detection: calibration broken down by destination postal code, not just city. Response: quarantine those postal codes to the distance-band fallback.
I would measure the service on promise accuracy, meaning share of orders delivered on or before the promised date, and on promise stability, meaning how often the date shown at checkout changes after purchase. A model that is accurate but changes the date three times erodes trust just as much. Both metrics go on the same dashboard, split by lane and carrier, because an aggregate number hides exactly the lanes that are broken.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-5Design a service that shows sellers on a marketplace their live order counts?
Reported in Allegro Interview: Devskiller Test, Rounds, Pay
The 90-second answer
I would treat this as a streaming aggregation problem, not a query over the orders table. Order creation already emits an event, so I consume that stream, count per seller in near real time, and serve the count from a cache that the API can read in single-digit milliseconds.
Assumptions I would state up front: a "live count" means orders created in the last 24 hours, excluding cancelled orders, grouped by seller. If the product wants counts by status, I add a status dimension to the same pipeline. The seller sees only their own number.
Order service --(orders.created, key=seller_id)--> Kafka
|
Flink job
dedup by order_id, 1-min buckets
|
Redis Cluster (hourly buckets)
|
Seller app <-- GET /sellers/me/order-counts <-- API (auth + cache)
|
Postgres (reconciliation only)Why hourly buckets
A single counter per seller with a 24-hour TTL cannot expire cleanly. When the TTL fires, the whole day disappears at once. Hourly buckets avoid that. The Flink job increments seller:{id}:h:2026051314 for the current hour. The API sums the last 24 buckets with one MGET. That is 24 keys, one round trip, and the count slides forward every hour instead of resetting at midnight.
Flink SQL for the aggregation, checked against Flink 1.19:
CREATE TABLE orders_created (
order_id STRING,
seller_id STRING,
created_at TIMESTAMP(3),
status STRING,
PRIMARY KEY (order_id) NOT ENFORCED
) WITH ('connector' = 'kafka', 'topic' = 'orders.created',
'properties.bootstrap.servers' = 'kafka:9092',
'format' = 'avro');
INSERT INTO seller_hourly_counts
SELECT seller_id,
DATE_FORMAT(created_at, 'yyyyMMddHH') AS hour_bucket,
COUNT(*) AS cnt
FROM orders_created
WHERE status <> 'CANCELLED'
GROUP BY seller_id, DATE_FORMAT(created_at, 'yyyyMMddHH')The primary key on order_id gives dedup in Flink state. A replayed Kafka record does not double count. State TTL of 48 hours bounds memory.
Scale, with labelled hypothetical figures
Suppose Allegro peaks at 8,000 order events per second and 300,000 sellers are active in a day. Partitioning Kafka by seller_id keeps all events for one seller on one partition, so ordering per seller holds and Flink parallelism scales by partition count. I would run 24 Flink subtasks against 48 partitions to leave headroom.
Redis memory: 300,000 sellers x 24 buckets x roughly 60 bytes per key (key, value, overhead) is about 430 MB. That fits on three Redis Cluster shards with replication, and each bucket carries a 48-hour TTL so idle sellers disappear on their own. Reads are MGET on keys that hash to the same slot if I use a hash tag, seller:{42}:h:..., which keeps the 24 keys on one node.
Read path target: p99 under 20 ms from Redis, versus 200 ms or more for a COUNT(*) over an orders index at this volume, which also competes with checkout writes for the same table.
Worked trace
Seller 42 gets orders at 14:03, 14:07 and 14:07 (duplicate delivery of the second). Flink emits one increment for the first, one for the second, and drops the duplicate on the order_id key. Redis now holds seller:{42}:h:2026051314 = 2. At 14:10 the seller opens the dashboard. The API authenticates the seller token, derives seller_id = 42 from the token rather than trusting a query parameter, runs MGET over the 24 hour buckets, and returns {"count_24h": 137, "as_of": "2026-05-13T14:10:00Z"}. The as_of timestamp matters. It tells the client the number is current to within the pipeline lag, which I would alert on above 30 seconds.
Failure modes and how I would detect them
| Failure | Effect | Detection and response |
|---|---|---|
| Kafka consumer lag grows | Counts go stale | Alert on lag > 30 s; autoscale Flink subtasks; dashboard shows as_of so staleness is visible |
| Redis shard evicts or fails | Reads fail or undercount | Replication across shards; API falls back to a Postgres aggregate query and caches the result for 60 s |
| Duplicate or replayed events | Overcount | Dedup on order_id in Flink state; hourly reconciliation job compares Redis totals against Postgres and writes a correction bucket |
| Order service emits a late cancellation | Count includes a cancelled order | Cancellation events update the same hourly bucket with a decrement; reconciliation catches anything missed |
The reconciliation job is the safety net I would insist on. Every hour it recomputes per-seller counts from Postgres for the previous day and diffs them against Redis. A diff above 0.1% pages the on-call. That turns silent drift into a number someone owns.
Security and access control
The endpoint takes no seller_id from the client. The seller identity comes from the authenticated token, and the API builds Redis keys from that identity only. That closes the obvious hole where a seller enumerates other sellers' counts by changing an ID. I would also rate limit per seller, serve over TLS, and keep order IDs out of the response since the count is the only data the seller needs. Kafka topics and Redis stay on a private network with no public ingress.
What I would not do
I would not poll the orders table from the API, and I would not push updates to the seller over WebSockets for a number that changes a few times a day for most sellers. If the product later needs per-order live status, that is a different service with a different freshness budget. For counts, a 10 to 30 second lag is invisible to the user and far cheaper to run.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-6Two threads update a shared counter and the total comes out wrong. Explain why, and how you would fix it with a thread pool doing the work?
Reported in Allegro Interview: Devskiller Test, Rounds, Pay
The 90-second answer
counter++ is not one operation. It is read, add, write, and none of those steps is atomic or ordered with respect to another thread. Two threads can read the same value, both add one, and both write back the same result. One update is lost. A thread pool does not fix that by itself. It only changes who runs the work. The fix is to make the update atomic, or to stop sharing mutable state in the first place.
For a data job I would prefer the second option. Split the input into partitions, let each pool task count its own partition into a local variable, return that partial count, and sum the partials after the futures complete. No contention, no lock, and the result is deterministic regardless of scheduling.
Why the total comes out wrong
Assume counter = 100 and two threads each run counter++ once:
| Step | Thread 1 | Thread 2 | counter in memory |
|---|---|---|---|
| 1 | read counter → 100 | 100 | |
| 2 | read counter → 100 | 100 | |
| 3 | compute 100 + 1 = 101 | 100 | |
| 4 | compute 100 + 1 = 101 | 100 | |
| 5 | write 101 | 101 | |
| 6 | write 101 | 101 |
Expected: 102. Actual: 101. The second write overwrites the first because both threads based their write on the stale value 100.
There is a second problem underneath the race. Without a happens-before edge, the Java Memory Model does not guarantee that a write by one thread is ever visible to another, or that reads and writes happen in program order. So even a thread that never overlaps in time can read a stale value. volatile alone fixes visibility, not atomicity. volatile int counter still loses updates in the trace above.
Fix 1: atomic update with a thread pool
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;
AtomicLong counter = new AtomicLong();
ExecutorService pool = Executors.newFixedThreadPool(4);
List<Future<?>> futures = new ArrayList<>();
for (int i = 0; i < 10_000; i++) {
futures.add(pool.submit(() -> {
for (int j = 0; j < 1_000; j++) {
counter.incrementAndGet();
}
}));
}
for (Future<?> f : futures) {
f.get(); // rethrows any exception from the task
}
pool.shutdown();
System.out.println(counter.get()); // 10_000_000incrementAndGet() uses a compare-and-swap loop internally. If another thread changed the value between the read and the write, the CAS fails and the operation retries. No update is lost.
Fix 2: partition and reduce, the version I would ship for counting
ExecutorService pool = Executors.newFixedThreadPool(4);
List<Future<Long>> partials = new ArrayList<>();
for (List<Record> partition : partitions) {
partials.add(pool.submit(() -> {
long local = 0;
for (Record r : partition) {
if (r.isValid()) local++;
}
return local; // local variable, never shared
}));
}
long total = 0;
for (Future<Long> f : partials) {
total += f.get();
}
pool.shutdown();Each task touches only its own local. The only shared write is the final sum on the main thread, after Future.get() establishes a happens-before edge from the worker. This scales with pool size. An AtomicLong under heavy contention does not, because every increment fights over one cache line.
Choosing between them
| Approach | Correct under contention | Scales with threads | When I use it |
|---|---|---|---|
synchronized block | Yes | Poorly, one lock serialises all updates | Counter is updated rarely, or the critical section already holds other state |
AtomicLong | Yes | Moderately, CAS retries grow with contention | A single shared total is genuinely required, for example a live progress gauge |
LongAdder | Yes | Well, updates are striped across cells and summed at the end | High-frequency increments where the exact value is only read at the end |
| Partition and reduce | Yes, by construction | Best, no shared writes at all | Counting or aggregating over splittable input, the common data engineering case |
Failure modes I would name in the interview
Swallowing exceptions. If a task throws and nobody calls get() on its future, the pool keeps running and the total is silently short. Calling get() on every future, as above, surfaces it.
Forgetting to shut the pool down. ExecutorService threads are non-daemon by default. A job that finishes its counting but never calls shutdown() hangs the JVM.
Unbounded submission. Submitting 10,000 tasks to a pool with an unbounded queue is fine here because tasks are tiny, but with large partitions the queue holds every partition in memory at once. I would bound the queue or submit in batches sized to the pool.
Picking synchronized out of habit for a counting job. It is correct, and it turns a 4-thread pool into a 1-thread pool for the update section. For a data pipeline that is the difference between a 10 minute job and a 35 minute one, which is why partition and reduce is my default answer.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-7Explain how the Java Memory Model affects what one thread sees of another's writes, and how a garbage collector such as G1 decides what to collect?
Reported in Allegro Interview: Devskiller Test, Rounds, Pay
The 90-second answer
The Java Memory Model (JMM, JLS 17.4) does not promise that a write by one thread becomes visible to another at any particular time. It promises visibility only when there is a happens-before edge between the write and the read. Without that edge, the second thread may see a stale value indefinitely, and the compiler and CPU are allowed to reorder or cache it. A garbage collector such as G1 then decides what to collect by reachability, not by reference counting: an object is live if it is reachable from a GC root through live objects at the moment G1 marks it. Everything unreachable, including cycles, is reclaimable.
For a data pipeline this matters in two places. A Kafka consumer or Flink task that hands a batch from a producer thread to a worker thread without a synchronization edge can process a half-built record. And a long-lived JVM that accumulates unreachable objects in old generation will pay for G1 marking and evacuation pauses even though the objects are garbage.
Visibility: what the JMM actually guarantees
Think of main memory as the shared heap and working memory as per-thread caches and compiler registers. The JMM abstracts the hardware and defines when a write in one thread must be visible to a read in another. The edges that create happens-before are narrow:
| Edge | Example |
| volatile write -> subsequent volatile read of same variable | flag = true (volatile) happens-before a read that sees true |
| Unlock -> next lock of same monitor | synchronized block exit, Lock.unlock() |
| Thread.start() -> first action in new thread | starting a consumer thread |
| Thread.join() returning -> last action of joined thread | shutting down a producer |
| Final field write in constructor -> read after construction completes | safely published immutable config |
Plain fields give no such edge. This is the classic unsafe publication bug:
// Java 17
class Batch {
int[] rows; // plain, not volatile, not final
boolean ready; // plain
}
class Producer extends Thread {
volatile Batch current; // volatile reference only
void publish() {
Batch b = new Batch();
b.rows = new int[]{1, 2, 3};
b.ready = true;
current = b; // volatile write: publishes b safely
}
}Here the volatile write to current creates a happens-before edge to any thread that reads current and sees the new reference. That reader is guaranteed to see rows and ready as written, because the writes to b happen-before the volatile write. Remove volatile and the reader can see current != null while rows is still null or ready is false. The compiler may also reorder b.ready = true before b.rows = ... in the absence of the edge.
A trace with the bug, on x86 with JIT inlining:
T1: b.rows = [1,2,3]; b.ready = true; current = b;
T2: if (current != null) { use(current.rows); } // may NPE or read ready == falseOn x86 the hardware store order often hides this in tests. On ARM, or after JIT reordering, it surfaces. That is why "it worked in staging" is not evidence. AtomicReference, ConcurrentLinkedQueue, and BlockingQueue all provide the needed edges internally, which is why handing work through a queue is safer than a plain shared field.
Two failure modes to name in an interview. First, double-checked locking on a plain field: the second check can see a partially constructed object. The fix is a volatile field or the holder idiom. Second, a static config object mutated after startup by an admin thread and read by worker threads: without volatile or synchronization, workers may run with the old config for the life of the JVM.
G1: how it decides what to collect
G1 (Garbage-First, default in JDK 9+ through current releases) divides the heap into equal regions, 1 MB to 32 MB, sized so there are at most 2048 regions. A 32 GB heap therefore uses 16 MB regions. Each region is young, old, or humongous (an object larger than half a region gets its own contiguous set of regions). There is no fixed young/old size. G1 keeps a soft pause target, MaxGCPauseMillis=200 by default, and grows or shrinks the young generation to try to meet it.
Collection is reachability from roots: thread stacks, static fields, JNI handles, and live objects. G1 uses SATB (snapshot-at-the-beginning) marking. When marking starts, it snapshots the set of objects reachable at that instant. If a mutator overwrites a reference during marking, the old object is still treated as live for that cycle, via a write barrier that records the overwritten reference in a SATB buffer. That trades a little extra retained garbage for correctness without stopping the world for the whole mark.
After marking, G1 knows the live bytes per region. It picks candidates garbage-first: regions with the lowest live ratio first, subject to the pause budget. A young collection copies survivors to new young regions. A mixed collection also includes some old regions with low live ratios. Copying uses remembered sets, per-region records of pointers from other regions, so G1 does not scan the whole heap to find references into a candidate region. Evacuation failure is the failure mode: if a region cannot be evacuated within the pause budget, G1 falls back to a fuller collection and the pause blows past the target.
Worked example, labelled hypothetical: heap 16 GB, region size 8 MB, 2048 regions. A mixed collection selects 40 old regions averaging 15% live. Live data to copy is about 48 MB, garbage reclaimed about 272 MB. If evacuation of those regions needs to copy 48 MB plus update remembered sets, and the budget is 200 ms, G1 may drop to 20 regions next cycle if the previous pause exceeded the target. The decision is economic: reclaim the most garbage per millisecond of copying.
What G1 does not collect is equally important for a data engineer. Off-heap memory, direct ByteBuffer memory, and native memory held by Spark or Kafka clients are invisible to G1. A consumer that allocates direct buffers faster than it releases them will hit OutOfMemoryError: Direct buffer memory while the Java heap looks healthy. Metaspace for generated classes and code cache are also outside the heap G1 manages. And an object reachable from a static cache, a never-cleared ConcurrentHashMap, or a thread-local in a pooled thread is live by definition, however stale the business data is. That is a leak the collector will faithfully preserve.
Putting it together in a pipeline
A typical Allegro-scale ingestion JVM runs a Kafka consumer thread, a deserialization stage, and a batching stage. If those stages share a plain List or a plain config flag, the JMM decides whether the batching thread sees the elements. Handing batches through a BlockingQueue or publishing through a volatile reference plus immutable batch objects removes the question. For G1, the operational signals are pause time versus MaxGCPauseMillis, allocation rate, and evacuation failures in the GC log (-Xlog:gc*). A rising old-generation occupancy with long marking phases usually means a reachable cache growing without bound, not a collector that needs tuning. Shrinking the cache or adding eviction fixes it. Raising the heap only delays it.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-8One microservice calls another over HTTP and the downstream service slows down. How do you set timeouts and retries so the caller stays healthy?
Reported in Allegro Interview: Devskiller Test, Rounds, Pay
The 90-second answer
I set a deadline for the whole call first, then split it into connect, read and write timeouts, then allow retries only inside that deadline and only for idempotent operations. If the downstream slows down, the caller fails fast, sheds load with a circuit breaker, and does not pile retries on top of a service that is already saturated.
Assume the caller is a service that enriches or validates records before writing them downstream, with a user-facing or pipeline SLA of 2 seconds end to end. I would not give the HTTP call the full 2 seconds. I reserve time for serialisation, queueing and the next step.
Total deadline: 2000 ms (propagated as a header, e.g. X-Deadline)
Connect timeout: 200 ms
Read timeout: 1200 ms
Write timeout: 300 ms
Retry budget: 1 retry, only if elapsed < 800 ms
Backoff: 100 ms base, full jitter, cap 500 ms
Circuit breaker: opens at 50% failures over 20 requests, 30 s openConnect is short because a connect timeout usually means a dead host or a full backlog, not a slow query. Read is the real budget. Write matters for large payloads. If I use Resilience4j in Java, or tenacity plus a deadline check in Python, the deadline is checked before every attempt, not just before the first.
Why retries are the dangerous part
A retry multiplies load. With 3 retries and no jitter, 100 requests per second from the caller become 400 per second at the downstream, exactly when it is struggling. That is the retry storm that turns a slowdown into an outage.
| Policy | Load at downstream when it slows | Caller p99 |
|---|---|---|
| No timeout, 3 retries | 4x, unbounded queueing | seconds to minutes, threads exhausted |
| 1200 ms read timeout, 1 retry, jitter | at most 2x, and only for fast failures | capped near 2 s |
| Timeout plus retry budget of 10% | retries stop when budget is spent | fails fast, protects downstream |
I use a retry budget: retries are at most 10 to 20 percent of total requests in a rolling minute. Once the budget is spent, the caller returns a 503 or a cached or degraded result instead of retrying. Full jitter means each retry waits a random time between 0 and the capped backoff, so clients do not retry in lockstep.
Only retry on timeouts, connection resets and 502, 503 and 504. Never retry on 400, 404 or 422. And only retry if the operation is idempotent or carries an idempotency key. A GET is safe. A POST that creates a record or charges something needs a key such as Idempotency-Key: <event_id> so the downstream can deduplicate the second attempt.
Worked trace
Downstream p99 has risen from 300 ms to 900 ms. Caller deadline is 2000 ms.
- t=0 ms: attempt 1 starts. Read timeout 1200 ms.
- t=900 ms: attempt 1 succeeds. Total 900 ms. No retry needed.
- Worse case: attempt 1 times out at 1200 ms. Elapsed is already over the 800 ms retry cutoff, so no retry is issued. The caller returns 503 with
Retry-Afteror serves a stale value, and records the failure for the circuit breaker. - Fast failure case: attempt 1 returns 503 in 80 ms. Elapsed is under 800 ms, budget remains, so attempt 2 starts after a jittered wait of, say, 60 ms. If attempt 2 also fails fast, the caller stops. Two attempts, not four.
That cutoff is the key detail. Retrying after a full read timeout almost never helps, because the downstream is slow rather than briefly unavailable, and the retry will also be slow.
Protecting the caller when the downstream stays slow
Timeouts alone do not protect thread pools. I add three things. A bulkhead: a separate connection pool and thread pool for this downstream, sized from its p99 and target throughput, so one slow dependency cannot starve calls to other services. A circuit breaker: after the failure threshold, calls fail immediately for 30 seconds while a few probe requests test recovery, which stops the caller burning its pool on a dead dependency. Load shedding at the edge: if the caller queue grows, reject or degrade early rather than queueing work that will miss its deadline anyway.
I watch four signals: caller p99 and timeout rate, retry rate as a share of total requests, circuit breaker state changes, and downstream queue depth or active connections. If timeouts rise but retries stay flat and the breaker opens, the policy is working. If retries climb while downstream latency climbs, the budget is too generous.
I would not use hedging, sending a second request in parallel after a delay, for a data pipeline call. It doubles load on a struggling service and only pays off for read-only calls with very tight latency targets and spare capacity downstream.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-9You are given a class that applies discounts to a shopping cart. Which tests would you write for it, and what would you comment on in a code review?
Reported in Allegro Interview: Devskiller Test, Rounds, Pay
The 90-second answer
I would first pin down the contract before writing tests, because discount code fails in production through ambiguous rules, not through a missing assertion. I need to know: are discounts applied per line or on the whole cart, in what order, can they stack, what is the rounding rule, and is the result deterministic for the same input. Money must be integer minor units or BigDecimal with an explicit scale, never double. If those answers are not in the spec, my first code review comment is that the class is untestable as written.
Assume a cart of lines, each with SKU, quantity, unit price in grosz, and a list of discount rules with priority. The class should be a pure function: Cart -> PricedCart. No database, no clock, no random, no mutation of the input. That one decision makes the tests below cheap and makes the output safe to replay in a pricing pipeline.
Tests I would write
Unit tests cover the rules in isolation. Property tests cover the invariants that must hold for any cart. A small integration test covers the one external dependency that matters, usually the rule lookup.
// JUnit 5, Java 17. Money in minor units (grosz).
@ParameterizedTest
@CsvSource({
"19999, 1, 0, 19999", // no rule matches
"19999, 1, 1000, 17999", // 10% off, 1999.9 rounds to 2000
"19999, 2, 1000, 35998", // per line, then sum: 2 * 17999
"333, 3, 1000, 899" // 333*0.9=299.7 -> 300 per line, 3*300
})
void appliesPercentagePerLine(long unit, int qty, int bps, long expected) {
var cart = Cart.of(Line.of("SKU-1", qty, unit));
var priced = service.price(cart, List.of(Rule.percent(bps, 1)));
assertEquals(expected, priced.totalMinor());
}The last row is the one I would defend in the interview. Rounding per line gives 900, rounding on the total gives 899. Neither is wrong in isolation. The bug is when the checkout service rounds per line and the warehouse or finance pipeline rounds on the total, and the two totals drift by a grosz per order. At Allegro scale that becomes a reconciliation break across millions of orders, and it surfaces in the data warehouse as a pricing mismatch nobody can reproduce. So the test documents the chosen rule and a second test asserts the same rule is used when the cart is repriced from stored events.
| Case | Input | Expected | What it catches |
|---|---|---|---|
| Empty cart | no lines | total 0, no exception | NPE on reduce over empty list |
| Zero quantity line | qty 0 | line excluded, total unchanged | negative or phantom lines |
| Fixed discount larger than line | 500 off a 300 line | line floored at 0, excess not carried to other lines unless spec says so | negative totals leaking downstream |
| Two stackable rules | 10% then 500 off | order fixed by priority, result documented | order dependence hidden in list order |
| Two mutually exclusive rules | both match | higher priority wins, other ignored | double discounting |
| Boundary percent | 0 bps, 10000 bps | 0 bps is a no-op, 10000 bps gives 0 | off-by-one and overflow in bps math |
| Large cart | 10,000 lines | completes, no quadratic behaviour | O(n^2) rule matching per line |
| Same input twice | identical cart | identical output, input cart unchanged | hidden mutation, clock or random use |
Property tests with jqwik or ScalaCheck would assert, for generated carts: total is never negative, total never exceeds the undiscounted sum, a higher percent never produces a higher total, and repricing a priced cart is idempotent. Those invariants catch whole classes of bug that example tests miss.
What I would comment on in code review
First, money and rounding. Any double or float for price, or a BigDecimal constructed from a double, is a blocker. I would ask for minor units as long, or BigDecimal with RoundingMode.HALF_UP and scale 2 stated at the boundary, plus a named constant for the rounding mode so finance can find it.
Second, purity and mutation. If applyDiscounts mutates the cart, sorts it in place, or reads the current time to decide whether a promo is active, I would ask for an immutable input and an explicit now parameter. In a data pipeline that class will be rerun over historical events. A hidden clock makes backfills produce different prices for the same order, and the audit trail stops matching the warehouse.
Third, rule ordering and stacking. If priority is implicit in the order rules happen to be returned from a database query, that is a defect. I would ask for an explicit priority field, a deterministic tie-break, and a test where the query returns rules in reverse order and the result does not change.
Fourth, failure behaviour. What happens on an unknown rule type, a missing SKU price, or a percent above 100? Silently skipping the rule hides a data problem and produces a wrong price that looks plausible. I would prefer a loud failure with the rule id in the exception, so the bad rule is caught before it reaches orders, and a metric counts it.
Fifth, observability without leakage. Log the rule ids applied and the before and after totals at debug level, never the full cart with buyer identifiers. The priced output should carry the applied rule ids per line, because downstream analytics and customer support need to explain a price without re-running the engine.
Failure modes I would name
Floating point drift, which shows up as one grosz differences between services. Stacking order drift between checkout and batch repricing. A rule that matches on a string field with inconsistent casing or whitespace, which passes tests with clean fixtures and fails on real catalogue data. And integer overflow when quantity times unit price exceeds int range, which is why the arithmetic above uses long.
If I had to pick the single test that matters most, it is the repricing test: price a cart, persist the priced result, reprice it a week later from the same inputs, and assert byte-for-byte equality. That is the test that protects the warehouse, the invoice, and the customer from disagreeing about what was charged.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-10Tell me about a decision you made based on data. What did the numbers show?
Reported in Allegro Interview: Devskiller Test, Rounds, Pay
The 90-second answer
At my last marketplace role we had a proposal to rebuild the seller dashboard feed as a streaming pipeline. I pushed back, and we shipped hourly incremental Spark instead. The decision came from 14 days of query logs, not from a preference for batch.
We had 340M order events a day, about 2.1 TB raw in Parquet. The dashboard query that everyone worried about, seller order counts for the last 7 days, ran 4m 12s at p95 and scanned 1.8 TB. I sampled query_history for the dashboard service account and classified the 41,000 queries in that window:
| Query pattern | Share of queries | Share of scanned bytes | Freshness actually needed |
|---|---|---|---|
| Last 7 days, grouped by seller | 61% | 74% | 4 hours |
| Yesterday or earlier, reconciliation | 17% | 19% | Next day |
| Today, intraday | 22% | 7% | 15 minutes for 3% of sellers |
Only the intraday slice needed sub-hour freshness, and even there the product spec said 1 hour was acceptable for the launch. A Kafka plus Flink build would have given us 1 minute freshness for a use case that was 78% historical. The streaming estimate was 48 streaming slots continuously, roughly 3.2x the compute cost of our hourly Spark job, plus a new exactly-once dedup path for late events.
So I proposed hourly micro-batches with a watermark, and we kept the daily reconciliation job untouched.
What we built
The raw table is partitioned by ingestion hour, not event time. Each hourly run reads exactly one ingestion-hour slice, aggregates it by seller and event day, and merges that slice into a Delta Lake aggregate table. Delta Lake on Spark 3.5 supports MERGE INTO; plain Parquet tables do not, which is why the aggregate is Delta and not Parquet.
-- Spark 3.5 with Delta Lake 3.1, checked against Delta docs
-- run_hour is the single ingestion hour being processed, e.g. '2024-05-01 14:00'
MERGE INTO seller_order_counts_daily AS target
USING (
SELECT seller_id, DATE(event_time) AS day,
COUNT(*) AS orders, SUM(amount_pln) AS gmv_pln
FROM orders_raw
WHERE ingestion_hour = TIMESTAMP '${run_hour}'
GROUP BY seller_id, DATE(event_time)
) AS source
ON target.seller_id = source.seller_id AND target.day = source.day
WHEN MATCHED THEN UPDATE SET
orders = target.orders + source.orders,
gmv_pln = target.gmv_pln + source.gmv_pln
WHEN NOT MATCHED THEN INSERT VALUES (source.seller_id, source.day, source.orders, source.gmv_pln);The source is one hour only, so an event is added once, when its ingestion hour is processed. A late event for yesterday that arrives today lands in today's ingestion hour and is added to yesterday's seller-day row then. That is the point of partitioning by ingestion time.
Idempotency comes from a small Delta table, processed_ingestion_hours(run_hour, row_count, merged_at). The job checks it before merging and inserts into it in the same Delta transaction pattern we used for staging: write the hourly aggregate to staging, verify its row count against the source slice, merge, then record the hour. A retry for an already recorded hour exits without merging, so it cannot double count.
The daily reconciliation is separate. It recomputes seller-day totals for the previous day directly from raw and overwrites those rows with UPDATE SET orders = source.orders semantics, not addition. That catches anything the hourly path missed, such as a source file that landed after its ingestion hour was processed.
What the numbers showed after launch
Hourly job runtime went from 38 minutes for a full daily recompute to 4 to 6 minutes per run, scanning about 90 GB instead of 1.8 TB. Dashboard p95 dropped from 4m 12s to 11 seconds because it now reads the small aggregate table, 18 GB total, instead of raw events. Freshness met the 1 hour spec for 99.1% of seller-days. The remaining 0.9% were late POS sellers, corrected within 24 hours by reconciliation, which we surfaced in the UI as a data_as_of timestamp so sellers could see it.
We measured late arrival to size the reconciliation window: 91% of events arrived within 1 hour of event time, 97.5% within 12 hours, 99.2% within 48 hours, and 0.3% after 72 hours, mostly from one offline POS integration. Those stragglers do not break the hourly merge, because they are counted in the hour they arrive, but reconciliation guarantees the day converges even if an ingestion partition is delayed.
If the intraday share had been above 40% of scanned bytes, or if the spec had required under 5 minutes, I would have argued for streaming. With the actual mix, hourly gave us the freshness sellers used, at a third of the cost and without a new streaming stack to operate.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-11Describe an improvement you introduced that nobody asked for?
Reported in Allegro Interview: Devskiller Test, Rounds, Pay
The 90-second answer
I added a data quality gate and a late-data reconciliation job to our daily orders pipeline, even though the ticket only asked for a new seller report. The report was easy. The pipeline underneath it was not trustworthy, and I had already seen it silently drop records twice.
Context, from a previous marketplace role: we ingested roughly 40 million order events a day into Hive via Kafka and a Spark job that wrote orders_daily partitioned by ds. The report needed orders_daily by seller. I started by profiling the table for the last 30 days before writing any SQL for the report.
Two problems showed up in that profile. First, about 0.3% of events arrived more than 24 hours late, after the partition for their event date had been closed. They landed in the next day's partition or were dropped by the dedupe step, so seller totals drifted by up to 1.8% on busy days. Second, a schema change upstream renamed seller_id to seller_ref in a producer release. The Spark job kept running because we read with SELECT * and cast by position in one place, and the report showed zeros for a whole seller segment for six hours before anyone noticed.
Nobody had asked for a fix. The ask was a dashboard. I shipped the dashboard on the existing table, then put the improvement in the same pull request stack as a separate change so it could be reviewed and reverted on its own.
What I built
A pre-merge check in the Airflow DAG, before the report task, that fails the run instead of publishing bad partitions. It checks row count against the previous 7-day median, null rate on seller_id, duplicate order_id within a partition, and that the partition's event-time max is within 36 hours of the watermark.
# Python 3.11, PySpark 3.5
ds = "2025-01-14"
df = spark.table("orders_daily").filter(f"ds = '{ds}'")
count = df.count()
null_rate = df.filter("seller_id IS NULL").count() / count if count else 1.0
dupes = count - df.select("order_id").distinct().count()
if not (0.7 * median_7d <= count <= 1.3 * median_7d):
raise ValueError(f"row count {count} outside 0.7-1.3x median {median_7d}")
if null_rate > 0.001:
raise ValueError(f"seller_id null rate {null_rate:.4f}")
if dupes > 0:
raise ValueError(f"{dupes} duplicate order_id rows")Second, a reconciliation job that reprocessed the last 3 days of raw events into a staging table, compared order_id sets against the published partitions, and wrote only the delta. That turned late arrivals from a silent error into a visible, bounded backfill.
| Before | After | |
|---|---|---|
| Late event handling | Dropped or misdated | Reconciled within 3 days, delta logged |
| Schema rename detection | 6 hours to notice | DAG fails in under 10 minutes |
| Seller total drift on peak days | Up to 1.8% | Under 0.05% in the following 4 weeks |
| Report publish | Always, even on bad data | Blocked until gate passes or is waived |
Trade-offs I weighed
I considered three options for the gate. A hard fail, which I shipped, blocks publication and forces a human decision. A soft alert publishes anyway and pages the owner, which keeps the dashboard fresh but lets bad numbers reach sellers. A quarantine table publishes the good rows and parks the rest, which is the most complex to build and the hardest for report consumers to reason about, because totals then depend on which rows were quarantined.
I chose the hard fail because this table fed seller-facing totals and a wrong total is worse than a late one. I would not use a hard fail for an exploratory table, a new source with no stable baseline, or an internal dashboard where a late or approximate number costs nothing. In those cases a soft alert is enough, and a hard gate just creates waiver fatigue. I saw that fatigue in week one: the first version used a tight band and fired on normal Monday dips. I widened it to 0.7 to 1.3 times the median and added day-of-week comparison after two weeks of data. Waivers are explicit now. A run can be marked waived with a reason in the DAG, and that reason is written to the table lineage. Silent waivers were the thing I was trying to remove.
For late data I also weighed streaming with allowed lateness against batch reconciliation. Streaming would have handled late events in near real time, but our consumers were batch Hive tables and the report ran once a day, so a 3-day batch reconciliation was simpler and matched the actual freshness requirement. If the report had needed intraday seller totals, I would have pushed for the streaming option instead.
A trace from the first week
The gate fired on day 4. Row count was 61% of the 7-day median. I checked the raw Kafka topic lag and found a consumer group had been paused during a deploy. The old behaviour would have published a half-empty partition and the report would have shown a sales drop. With the gate, Airflow marked the task failed, the on-call got the alert with the failing check and the median, and we resumed the consumer and reran. No manual SQL fix to the published table.
The reconciliation job had a risk of double counting if it ran twice. I made it idempotent by deleting staging rows for the 3-day window and rebuilding from raw events keyed on order_id, then merging on that key. Rerunning it produced the same partition contents, which I verified by hashing the sorted order_id list before and after a forced rerun.
If I did it again I would add the same gate to the payments table first. Orders were visible to sellers, so the drift got reported quickly. Payments had the same late-arrival pattern and a longer detection time, which I only realised after the orders fix was already in production.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-12Tell me about a goal you set for yourself or your team, and how you measured it?
Reported in Allegro Interview: Devskiller Test, Rounds, Pay
The 90-second answer
I set a goal for our orders pipeline team, not a vague one about improving quality. The goal was to cut the share of seller order records that needed manual reconciliation from 4.2% to under 0.5% within one quarter, without increasing pipeline cost per million events by more than 10%.
That came from a concrete pain point. At the marketplace scale I was working at, roughly 18 million order events a day landed in the warehouse. About 4.2% arrived late, duplicated, or with a missing seller_id, so finance and seller reporting disagreed with the operational store. The team spent Fridays fixing partitions instead of shipping features.
I measured the baseline first, for two weeks, before changing anything. The metric was defined in one SQL query so nobody could move the goalposts later:
-- checked against warehouse tables, daily grain
SELECT
event_date,
COUNT(*) AS events,
SUM(CASE WHEN seller_id IS NULL
OR event_time < ingestion_time - INTERVAL '6' HOUR
OR is_duplicate THEN 1 ELSE 0 END) AS bad_events
FROM orders_events_raw
GROUP BY 1;Bad rate = bad_events / events. Baseline: 4.2% on weekdays, 6.1% on Mondays after weekend backfills. I also tracked two guardrails: p95 end-to-end latency from event to curated table, and cost per million events from the compute bill divided by event count.
What I changed
We split the work into two tracks. First, at ingestion, we added a deterministic dedup key (order_id, event_type, event_version) and a quarantine table for events missing seller_id instead of dropping them silently. Second, we moved the late-arrival handling from a nightly batch fix to a streaming upsert with a 6-hour watermark, so late events corrected the curated table within the hour rather than the next day.
I owned the measurement and the rollout plan. We shipped to 5% of sellers in week 3, 50% in week 5, and 100% in week 7. Each step had a rollback trigger: if bad rate did not fall by at least 1 percentage point, or p95 latency rose above 25 minutes, we stopped and investigated.
Result, with the arithmetic
| Metric | Baseline | After 12 weeks | Target |
|---|---|---|---|
| Bad events | 4.2% | 0.38% | < 0.5% |
| Monday bad events | 6.1% | 0.71% | < 1.0% |
| p95 event to curated | 18 min | 22 min | < 30 min |
| Cost per 1M events | 1.00x | 1.07x | < 1.10x |
At 18 million events a day, dropping from 4.2% to 0.38% meant roughly 690,000 fewer bad records per day. Manual reconciliation tickets fell from about 140 a week to 11. The 7% cost increase came from the streaming upsert, and we accepted it because the guardrail was explicit from the start.
What I would do differently
I set the goal on the curated table, but the first two weeks of complaints came from a downstream seller dashboard that cached hourly. The pipeline was correct and the dashboard still looked wrong. Next time I would add a consumer-level check, a daily reconciliation between the curated table and the dashboard aggregate, as part of the goal definition rather than as a follow-up bug.
If an interviewer asks how I chose the target, the honest answer is that 0.5% was not arbitrary. Below about 0.4% the remaining bad events were mostly genuine seller-side clock skew, which we could not fix from our side. I set the target just above the floor we could actually reach, and I said so in the goal document.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-13Describe a time you worked with another team to deliver something you could not do alone?
Reported in Allegro Interview: Devskiller Test, Rounds, Pay
The 90-second answer
At my last marketplace, I owned the daily seller settlement dataset, but I could not ship it alone. Finance owned what a seller was owed, the backend team owned the transactional tables that recorded orders, refunds and fees, and my team owned the pipeline that turned those tables into a number finance would sign off. The first version failed because each team optimised its own piece. We fixed it by agreeing one contract, one reconciliation check and one owner per field, then rebuilding the pipeline around an outbox event stream instead of nightly table dumps.
What happened
Sellers were paid weekly, but finance and sellers kept getting different totals. Our warehouse said PLN 18.4m for a settlement week, finance said PLN 18.1m. The gap was not a bug in one query. Refunds landed in the payments table up to three days after the order table closed, fee rules changed mid-week, and the backend team had added a new fee_type without telling anyone. I could add more joins. I could not decide whether a refund after payout should claw back from the next settlement or from the original one. That was a finance policy decision, and the backend team had to expose the refund timestamp that made the policy enforceable.
We formed a small group: me, one backend engineer who owned orders and payments, and one finance analyst who owned the settlement rules. We wrote the contract down before writing pipeline code.
| Area | Owner | Agreed rule |
|---|---|---|
| Fee and refund policy | Finance | Refund after payout reduces next settlement, recorded with refund_ts |
| Order, payment, refund events | Backend | Published via outbox in same transaction as the write |
| Settlement model and tests | Data | One row per seller per settlement week, reproducible from events |
| Break report | Data, reviewed by Finance | Daily count of sellers where warehouse total differs from ledger by more than PLN 1 |
The backend change was the part I could not do. They added an outbox table and a relay that published to Kafka. My consumer then looked like this in outline:
# consumer checked against Python 3.11, Kafka via confluent-kafka
for msg in consumer:
event = parse(msg.value())
if event.event_id in seen_ids: # idempotency store, 7 day TTL
continue
apply_to_staging(event) # upsert on (order_id, event_type, event_id)
mark_seen(event.event_id)That gave us replay safety. If the consumer crashed after applying an event but before committing the offset, the replay was a no-op instead of a double counted fee.
The trace that convinced finance
For one seller in the test week, the old nightly job produced one number. The new flow produced a trace finance could audit:
order o_9912 2024-03-04 10:12 gross PLN 240.00 fee PLN 28.80
refund r_118 2024-03-06 09:40 gross PLN -240.00 fee PLN +28.80 (reversed)
payout p_77 2024-03-08 00:00 settlement week W10, refund applied hereVolume was modest by Allegro standards, about 40m order and payment events a day in my example, but the point was ordering and completeness, not throughput. We partitioned by order_id so events for one order stayed in order, and we kept a late event table for anything arriving more than 24 hours after event_ts. Late events triggered a restatement of the open settlement week, not a silent overwrite of a closed one.
Result and what I would repeat
Break rate fell from 4.2% of sellers per week to 0.3% in the first month, and the remaining breaks were almost all late refunds, which finance accepted as a known category. Freshness went from next morning to about 15 minutes for the staging tables, which let finance run the break report before payout instead of after complaints.
The argument I lost was useful. I wanted the backend team to publish a denormalised settlement_line event so my job stayed simple. They refused, correctly, because that would have put finance policy inside their transactional service and made every fee change a backend deploy. We kept policy in the warehouse model, where finance could review it in SQL, and kept the backend contract to facts: what happened, when, and the id to deduplicate on.
If I joined Allegro, I would expect the same shape in a marketplace setting. The data team rarely owns the source of truth for offers, orders or payments. The win comes from making the other team the owner of the event contract and keeping the business definition where the business can read it, then proving both with a reconciliation number neither team can argue with.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-14Why do you want to work at Allegro?
Reported in Allegro Interview: Devskiller Test, Rounds, Pay
The 90-second answer
I applied to Allegro because the data problems I want to keep solving are the ones a marketplace creates, and Allegro is the clearest version of that in this market. I have worked on event pipelines for a retail group where order, payment and stock events came from different systems and rarely agreed. The work that mattered was reconciliation. A dashboard could be rebuilt. A seller payout could not.
Allegro runs Allegro Pay and the Allegro One delivery programme alongside the marketplace itself. That matters to me because the interesting failures sit between those systems. An order is created, paid, picked, shipped and settled, and each step produces its own version of the truth. I want to work where that chain is owned end to end, rather than where I only receive a cleaned feed from another company.
What I would expect to do in the first months
I would start by learning how order and payment events are keyed today, and where duplicates or late arrivals are handled. In my last role we processed about 2 million order events a day through Kafka into Spark Structured Streaming, with a 15 minute micro batch. That setup was fine for internal reporting. It was not fine for anything a seller saw the same day. We moved the seller facing counts to a separate path with deduplication on order ID plus event type, and we kept the batch path as the reconciling source. The lesson I took from that is that freshness and correctness need different pipelines, and someone has to own the comparison between them.
At Allegro I would want the same ownership. Ingestion that quarantines malformed events instead of dropping them. A replay path for a producer schema change, because a courier or payment partner will change a field without telling us. Checks that compare streaming totals against the transactional source before a payout or a delivery promise is published. Those are concrete things I have done, and they are the things I would volunteer for here.
How I weighed the choice
| Option I considered | What attracted me | Why I did not choose it |
|---|---|---|
| A pure payments company | Deep work on settlement and fraud signals | I would lose the marketplace side, the catalogue, search and logistics events that make the data interesting to me |
| A smaller marketplace | Faster decisions, broader ownership | Fewer concurrent producers, so less pressure on exactly-once handling and schema evolution, which is the part I want to get better at |
| Staying in my current retail role | I know the systems and the people | The roadmap was moving toward managed reporting tools, and the streaming work I care about was being deprioritised |
Allegro came out ahead on the criteria I set before applying. The role description named streaming and event driven pipelines rather than only warehouse modelling. The team sits with product consumers instead of serving tickets from a central queue. And the business gives the data a visible consequence. A wrong delivery estimate or a wrong seller balance is noticed quickly, which keeps the engineering honest.
There are conditions where this would be the wrong move, and I checked for them in the loop. If the team turned out to be a ticket queue with no ownership of ingestion, I would not take it. If the work were only scheduled batch loads into a warehouse, I would not take it either, because that is not the direction I want my next three years to go. If the on call expectations for streaming pipelines were unclear, I would ask again before signing. I am choosing Allegro for the specific shape of the work, and I am prepared to walk away if that shape is not real.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Curated: · Written: · Reviewed: