Skip to content
Tech Interview Prep

Real Interview Questions for the Software Engineer at Allegro

New

Interview Q&A

15 questions · Flow follows Relevance until this set has a learning order.

Q&A-1Why Do You Want to Work at Allegro?

Reported in How to Answer: "Why Do You Want to Work at Allegro?"

The 90-second answer

"I want to work at Allegro because the engineering surface matches the work I want to keep doing. I have built order and payment services where a retry after a timeout could create a duplicate charge, and I want to work on that problem at marketplace scale, with payments, delivery and search all coupled. Allegro is the Polish marketplace founded in Poznan in 1999, and it now runs Allegro Pay, Allegro One delivery, Allegro Logistics and Allegro Ads alongside the core marketplace. That coupling is the attraction. A change in the delivery promise affects checkout conversion, warehouse load and carrier handoffs in the same release window. I want a team where that kind of cross-system reasoning is the normal job, not an exception."

That opening does three jobs. It names products I would actually touch, it states a technical problem I have already handled, and it gives a criterion I can be tested against in follow-up. Praise for the brand does none of those.

Why this company, judged against alternatives

I considered three kinds of employer for this move, and the deciding criteria were scale, coupling and feedback speed.

OptionWhat you getWhat you loseDeciding factor for me
Pure retail platformDeep catalogue and fulfilment expertisePayments and seller tooling are secondaryLess coupling between checkout and third-party sellers
Pure payments companyHardest money-movement problemsSearch, delivery promise and seller experience sit outside your teamNarrower product surface
AllegroMarketplace, payments, logistics and ads in one systemMore coordination across teams, more Polish-language stakeholder contextCoupling plus peak traffic I can measure

If the role I am interviewing for were platform infrastructure only, my answer would change. I would pitch capacity planning and rollout safety instead of product coupling, and I would say so. Pretending interest in search when the team is infrastructure is a mismatch the interviewer will find in two questions.

A concrete trace I would use in the loop

Suppose checkout calls Allegro Pay, the call times out at 2 seconds, and the client retries. Without an idempotency key, the retry can create a second payment authorisation. With a key, the first request stores key -> payment_id and the retry returns the stored result. I would walk through that trace, then ask how the team handles the harder case: the first request succeeded downstream but the response was lost, and the key store itself is unavailable during a peak. That follow-up shows I care about failure handling, not just the happy path.

For peak load, I would use labelled hypothetical figures rather than quoting Allegro numbers I cannot verify. If checkout traffic rises 6x for four hours on a promotional day, a service that is comfortable at 2,000 requests per second needs headroom to 12,000, plus retry amplification. At a 5% retry rate, that adds roughly 600 requests per second of duplicate work. The question I would ask the team is how they load test that shape, with retries included, instead of testing a flat line.

Failure modes for this answer

The first is team mismatch. If I pitch Allegro Pay and the offer is for a data platform team, I need a prepared second version of the answer that explains what transfers, for example event pipelines and reconciliation, and what does not. Without it, I sound like I only want one team.

The second is invented scale figures. Citing active buyers, sellers or transaction counts from memory, with a year attached, invites a correction. A general statement about Poland's largest marketplace plus a question about current peak traffic is safer and still specific.

The third is relocation and language vagueness. Allegro's engineering is largely in Poznan and Warsaw, and much day-to-day work is in English, but stakeholder work with Polish sellers and carriers is not. I would state my position on relocation and on working in English with Polish-speaking partners, rather than leaving it to be discovered later.

The fourth is sounding like I want stability. A candidate who says the company is well known and secure has given the interviewer nothing to probe. The stronger close is a first project: I would ask which team has the checkout retry or delivery promise problem I described, and what success looks like there in six months.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-2Tell 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

I would start with the metric that was hurting users, not the technology I wanted to add. On a marketplace search path I owned, p95 latency for GET /search had climbed from 210 ms to 480 ms over six weeks while traffic grew 30%. Error rate stayed flat, so this was not a bug. It was capacity and query shape.

I pulled three numbers before proposing anything: latency by percentile, where time went in the trace, and cache hit rate for the product catalogue service the search service called. p50 was 140 ms, p95 was 480 ms, p99 was 1.1 s. In sampled traces, 310 ms of the p95 was one downstream call that fetched full product documents to compute facets, even though facets only needed category_id, price_band and seller_id. Catalogue cache hit rate was 61%, and misses were concentrated on long-tail queries with no reuse.

That changed the decision. Adding more search replicas would have cut queueing but left the 310 ms call untouched. I proposed two smaller changes: return a slim projection for facet computation, and cache facet results by normalised query plus filters for 60 seconds. I estimated the cache needed a hit rate above roughly 45% to pay for its memory and invalidation cost at our query volume, and the trace data suggested we would clear that on head queries even if long-tail stayed uncached.

What the numbers showed after rollout

We shipped the projection first, behind a flag, to 10% of traffic. That is the part I would stress in the interview: the decision was staged so the data could prove me wrong.

MetricBeforeProjection only (10%)+ facet cache (100%)
p50 search latency140 ms118 ms96 ms
p95 search latency480 ms340 ms210 ms
p99 search latency1,100 ms820 ms430 ms
Downstream catalogue calls per search1.001.00 (smaller payload)0.38
Facet cache hit raten/an/a57%
Catalogue payload per call18 KB4.2 KB4.2 KB

Payload drop came from this change in the catalogue client:

Java
// Before: full document, then pick three fields in memory
ProductDoc doc = catalogue.get(productId);
Facet f = new Facet(doc.categoryId(), doc.priceBand(), doc.sellerId());

// After: projection pushed to the store
Facet f = catalogue.getProjection(productId,
    Set.of("category_id", "price_band", "seller_id"));

The arithmetic behind the cache call, using our actual volume at the time: about 2,400 searches per minute at peak, 57% hit rate, so roughly 1,030 downstream calls per minute avoided. At 4.2 KB per slim response that is about 4.3 MB per minute of internal traffic saved, and more importantly the p95 dropped because the remaining misses no longer queued behind the same connection pool. Memory cost was bounded: 60 second TTL, key capped at 200 bytes, estimated 40k live keys at peak, under 300 MB in Redis. If hit rate had fallen below 40% in the first week, the runbook said to disable the cache and keep only the projection, because then we would be paying memory and stale-facet risk for little gain.

Failure modes I watched for

Stale facets after a price change were the real risk, not latency. We keyed the cache on query and filters but invalidated on product_updated events for affected categories, and we logged facet mismatch rate against a shadow uncached computation for the first 48 hours. Mismatch stayed under 0.2%, which we accepted because facets are discovery aids, not checkout pricing. Checkout still read price from the order service.

The other failure mode was a hot key. One promotional query accounted for 8% of traffic. Without request coalescing, a TTL expiry would have sent a burst of identical catalogue calls at once. We added single-flight loading per key, so the first miss fetched and the rest waited on the same future.

If I were doing it again I would instrument earlier. We had latency percentiles and traces, but no per-query-shape breakdown, so the first week of investigation was spent proving the long tail was not the problem. Adding query_shape as a low-cardinality label to the search metrics would have cut that to a day.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3Describe an improvement you introduced that nobody asked for?

Reported in Allegro Interview: Devskiller Test, Rounds, Pay

The 90-second answer

At my previous role we ran a seller-facing orders API. Nobody had asked for performance work on it. I noticed it in the slow-query log while debugging something else: GET /sellers/{id}/orders was scanning the full orders table for large sellers, and the page size was unbounded. I rewrote it with a composite index and keyset pagination, shipped it behind the existing endpoint, and measured it for two weeks before asking anyone to care.

The point I would make in the interview is that I did not start with a ticket. I started with a trace I could reproduce, a number I could defend, and a change small enough to revert in one deploy.

What I found

The old query filtered by seller and status, then sorted by creation time:

SQL
-- before, PostgreSQL 15, orders table ~18M rows (hypothetical figures from that role)
SELECT id, status, total, created_at
FROM orders
WHERE seller_id = $1 AND status = $2
ORDER BY created_at DESC
LIMIT 100;

For a seller with 400k orders, EXPLAIN ANALYZE showed a sequential scan plus a sort. p95 latency on that endpoint was 2.4 s, and it accounted for about 11% of database CPU during the evening peak. The frontend was also requesting limit=1000 on some screens, which made the tail worse.

The change

I added one index and changed the pagination contract internally, without breaking the existing response shape:

SQL
CREATE INDEX CONCURRENTLY idx_orders_seller_status_created
    ON orders (seller_id, status, created_at DESC, id DESC);
Java
// keyset cursor instead of OFFSET: stable under concurrent inserts
// cursor = (created_at, id) of the last row returned
List<Order> page = repo.findBySellerIdAndStatusOrderByCreatedAtDescIdDesc(
        sellerId, status, cursor, PageRequest.ofSize(50));

CONCURRENTLY mattered. A plain CREATE INDEX on 18M rows would have taken a lock that blocked writes during the day. The concurrent build took about 40 minutes and I ran it in a low-traffic window.

Measured result

Metric (2 weeks before vs 2 weeks after)BeforeAfter
p95 latency, GET /sellers/{id}/orders2.4 s180 ms
p99 latency5.1 s420 ms
DB CPU during evening peak68%31%
Slow queries (>1 s) per hour on this endpoint~340~12
Write latency on order insertbaseline+3 ms (index maintenance)

That last row is the trade-off I would name unprompted. The index costs writes. At our insert rate, roughly 900 orders per minute at peak, 3 ms was acceptable. If we had been at 20k inserts per minute, I would have needed a different conversation about partitioning or a read replica.

How I de-risked an unasked-for change

I did not announce a project. I opened a pull request with the EXPLAIN output, the before and after numbers from a staging copy with production-like data volume, and a rollback note: drop the index, the old query still works. I also capped limit at 100 server-side and returned a cursor, so clients asking for 1000 got 100 plus a next page instead of a timeout.

Two failure modes I checked explicitly. First, duplicate or skipped rows with OFFSET under concurrent inserts. Keyset pagination on (created_at, id) avoids that because the cursor is a position in the sort order, not a row count. Second, index bloat on a table with frequent status updates. Status changes update the indexed columns, so I monitored index size weekly for the first month. It grew 18% in the first week, then stabilised.

The team later adopted the same pattern for the returns endpoint, which nobody had scheduled either. That was the outcome I actually wanted: not credit for the index, but a repeatable fix the next person could copy without me in the room.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4Tell 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 team goal, not a personal one, because the problem crossed three services. Our checkout p95 was 1.8 seconds and 2.1% of attempts timed out at the payment step. I proposed we cut p95 to under 900 ms and timeouts to under 0.5% within one quarter, with checkout conversion as a guardrail. If conversion fell, we had not succeeded even if latency improved.

I wrote the definition down before we changed code. Latency came from server timing at the checkout API, p95 over completed and timed-out attempts, split by region. Timeouts came from the payment client error code, not from a generic 5xx bucket. Baseline was the prior four weeks, not a single bad day. We reviewed the same dashboard every Monday, and I owned reporting it even when the numbers moved the wrong way.

The first two weeks were measurement and tracing. We found the inventory check made a sequential call per basket line, and the payment client held a database connection while waiting on the provider. Those two facts explained most of the tail.

WeekCheckout p95Payment timeoutsCheckout conversion
Baseline, 4-week median1.80 s2.1%61.4%
After parallel inventory check1.15 s1.9%61.6%
After releasing DB connection before payment call0.82 s0.4%61.9%
Quarter end, 4-week median0.84 s0.4%61.8%

What we changed, and what failed first

We parallelised the inventory calls with a bounded fan-out of eight and added a 300 ms per-call deadline. That alone took p95 from 1.80 s to 1.15 s. The arithmetic was simple: a six-line basket was paying six sequential round trips of roughly 120 ms each.

My first idea for the payment step was to cache the provider token response for 60 seconds. It cut latency further, but stale token handling caused a spike in declined payments in the first canary, from 0.4% to 1.1% of attempts. We rolled that back the same day and kept the simpler change: release the database connection before the payment call, and move the connection pool from 20 to 40 for the checkout service only. Pool saturation had been the hidden cause of the timeouts. Once the pool filled, requests queued behind a payment call that could take two seconds.

How I know the measurement held

We did not declare victory on the week after deploy. The quarter-end figures above are a four-week median, so a single quiet week could not carry them. We also checked the split by region and by basket size. The improvement held in both regions, and the largest baskets, which had been the worst tail, improved most. That told me we had fixed the mechanism rather than shifting traffic.

The part I would repeat is freezing the metric definition up front. When someone later suggested reporting only successful checkouts, which would have flattered p95 by excluding timeouts, we kept the original definition. A goal you can redefine mid-quarter stops being a measurement and becomes a story you tell at review time.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5Describe 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

I was on checkout, and we were losing about 8% of payment attempts to avoidable failures. We could retry, but a blind retry would push more traffic into fraud checks and 3-D Secure challenges, which would hurt the good customers we were trying to save. The fix needed three owners: my team owned the checkout API, the risk team owned the scoring model, and the payments team owned 3-D Secure routing. None of us could ship it alone, so we ran it as one delivery with a shared contract and a shadow rollout.

We agreed the risk team would expose a synchronous score in under 300 ms, payments would expose a routing hint for the retry, and my team would own the orchestration, idempotency, and the experiment. After a four-week shadow period, payment success in the test group went from 91.2% to 94.8%, and the challenge rate for low-risk users fell by a fifth. The numbers are from that rollout, not a vendor estimate.

What we actually built

The flow was: checkout receives a payment attempt, calls risk once, then either retries directly, retries with 3-D Secure, or stops and shows a clear error. The hard part was not the code. It was the timeout budget. Risk initially quoted 800 ms. At checkout p99 that would have added almost a second to every payment, so we measured real traffic in shadow mode for two weeks. Their p95 was 140 ms and p99 was 260 ms once we removed a synchronous enrichment call they did not need for this use case. That measurement settled the argument.

The contract we locked before anyone wrote production code:

JSON
POST /risk/v1/score
{
  "attempt_id": "pay_9f31",
  "amount": 249.99,
  "currency": "PLN",
  "device_id": "d_118",
  "account_age_days": 412
}

200 OK
{
  "score": 0.18,
  "band": "low",
  "latency_budget_ms": 300,
  "model_version": "risk-2024-11"
}

My team treated a timeout or a 5xx from risk as "unknown", not "low". Unknown meant one direct retry and no 3-D Secure escalation. That rule came from the risk team, and it prevented a failure mode we had not considered: during their first deploy, their p99 spiked to 1.1 s for 20 minutes. Checkout degraded to the old path instead of failing payments.

WeekOwnerDeliverableExit check
1All threeContract and timeout budget signed offShadow traffic flowing
2-3RiskScore endpoint behind flag, no checkout dependencyp99 under 300 ms on shadow load
3-4PaymentsRouting hint for retry attemptsHint present on 99.9% of retries
4-6CheckoutOrchestration, idempotency key per attempt, 1% rolloutSuccess rate and challenge rate tracked by band

Where it nearly broke

Payments wanted to route every medium-band retry through 3-D Secure. That would have been simpler for them and worse for conversion. We ran the 1% cohort both ways for a week. The extra challenge step lifted success by 0.4 points in the medium band but dropped overall completion because users abandoned the challenge. We kept their routing for high band only, and I owned the rollback switch because my team owned the customer-facing flag.

What I would repeat

Start with the shared contract and the failure behaviour, not with sprint plans. Each team kept its own roadmap, but the interface, the timeout, and the "unknown" case were joint decisions. That is what made it deliverable. If I had built the retry logic alone and asked risk for a score later, we would have shipped a retry that either timed out or trained users to expect a challenge on every second attempt.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6Explain 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 reading thread may see a stale value, a partially constructed object, or values in an order the writing thread never wrote them. G1 then decides what to collect by reachability, not by reference counting: an object is live if it is reachable from GC roots through live objects at the moment of marking. G1 tracks that reachability concurrently with a snapshot-at-the-beginning (SATB) barrier, records cross-region references in remembered sets, and evacuates live objects out of regions whose garbage ratio makes them worth collecting.

Visibility: happens-before, not cache flushing

Think of main memory as an abstraction. Each thread may work with a cached copy, and the compiler and CPU may reorder reads and writes when no happens-before edge forbids it. The JMM defines edges from synchronization actions:

EdgeExample
Unlock to subsequent lock on same monitorsynchronized block exit to next entry
Volatile write to subsequent volatile read of same variablevolatile boolean ready
Final field write in constructor to read after construction completesfinal fields, if this does not escape
Thread start to first action in that threadnew Thread(...).start()
Thread termination to join() returningt.join()

Classic failure, unsafe publication:

Java
class Holder {
    int x;              // not final, not volatile
    Holder(int x) { this.x = x; }
}

static Holder holder;   // plain static field

// Thread A
 holder = new Holder(42);

// Thread B
 if (holder != null) {
     System.out.println(holder.x); // may print 0, not 42
 }

Thread B can see the reference to Holder before it sees x = 42, because there is no happens-before edge from the constructor write to B's read. The fix is to create the edge, for example with a volatile reference, a lock, or safe publication through a final field without this escaping during construction.

The same pattern explains the correct flag idiom:

Java
class Worker {
    int result;
    volatile boolean done;

    void run() {
        result = 42;
        done = true;      // volatile write
    }

    void read() {
        if (done) {       // volatile read
            System.out.println(result); // guaranteed 42
        }
    }
}

Trace: Thread A writes result = 42, then writes done = true. Thread B reads done == true. The volatile write happens-before the volatile read, and program order inside Thread A puts the result write before that. Transitivity gives result = 42 happens-before B's read of result, so B cannot see 0. Remove volatile and the trace breaks: B may see done == true and result == 0, or never see done change at all.

Two limits candidates should state. Happens-before gives visibility, not atomicity. counter++ on a plain int is a read, a modify, and a write, so two threads can both read 10 and both write 11. Use AtomicInteger, a lock, or a LongAdder when contention is high. Also, volatile does not make a multi-field update atomic. Publishing a whole immutable snapshot through a single volatile reference is the usual way to keep related fields consistent.

How G1 decides what to collect

G1 divides the heap into regions, typically 1 MB to 32 MB depending on heap size, each classified as young, old, or humongous at a given moment. Young regions hold new objects. Old regions hold survivors and long-lived data. A humongous object, larger than half a region, gets its own contiguous regions.

Collection is reachability based. GC roots include stack locals, static fields, JNI handles, live threads, and objects referenced by the JIT. If an object is reachable from a root through a chain of live objects, it is live. Cycles do not keep objects alive on their own. That is the practical difference from reference counting, which leaks cycles and cannot reclaim them promptly.

G1 marks concurrently using SATB. When marking starts, it snapshots the set of objects that were live at that instant. A write barrier records the old value of a reference being overwritten, so an object that was reachable at snapshot time stays marked even if the mutator drops the last reference during marking. That keeps marking correct without stopping the world for the whole cycle, at the cost of keeping some newly dead objects alive until the next cycle.

Cross-region references are tracked with a card table and remembered sets. When a mutator writes a reference into an old region pointing at a young object, the card for that old region is dirtied. During a young collection, G1 scans those cards to find roots into the young generation, instead of scanning the whole old generation. Card marking and SATB are the two barriers that make concurrent marking safe.

Evacuation is where G1 chooses. A young collection copies live young objects to survivor or old regions and reclaims the rest. A mixed collection also picks old regions with the highest garbage ratio, meaning the most dead bytes per byte copied, and evacuates their live objects. G1 scores candidate regions by predicted cost against the pause target, default 200 ms in older releases and configurable with -XX:MaxGCPauseMillis. If evacuation cannot fit the live data into the target space, the collection fails and falls back to a full collection, which is the failure mode to watch in production.

Concrete failure modes I would name in an interview: a large number of humongous allocations fragmenting old regions and forcing full collections; long reference processing pauses when there are many weakly or softly reachable objects to drain; and evacuation failure when a mixed collection underestimates live data after a traffic spike. The diagnostics are the GC log (-Xlog:gc*), region occupancy, humongous allocation counts, and the gap between allocation rate and reclamation rate. Tuning region size, pause target, and concurrent marking thresholds helps only after those numbers show which mechanism is actually binding.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7Two 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 three: read the current value, add one, write it back. Two threads can read the same value before either writes, so one increment overwrites the other. That is a lost update, and the final total ends up below the number of increments performed.

With a thread pool I would stop sharing a mutable int across tasks. Either use an atomic counter, or better, give each task its own local count and add those partial sums once at the end. The second option removes contention entirely and scales with the pool.

Why the total is wrong

Assume counter = 100, thread A and thread B both run counter++.

StepThread AThread Bcounter in memory
1read counter → 100100
2add 1 → 101read counter → 100100
3write 101add 1 → 101101
4write 101101

Two increments ran, the value rose by one. Run that interleaving a few thousand times in a loop of 1,000,000 increments per thread and you might get 1,998,431 instead of 2,000,000. The exact shortfall varies per run because it depends on scheduling, which is why the bug is hard to reproduce on demand and why it disappears under a debugger.

Two related traps are worth naming. volatile does not fix this, because it guarantees visibility of writes but ++ is still read, modify, write. And on a 64-bit long or double on older JVMs, even the read and write themselves were not guaranteed atomic. Modern JVMs make 64-bit reads and writes atomic, but the compound increment still is not.

Fix 1: atomic counter

Java
import java.util.concurrent.atomic.AtomicLong;

AtomicLong counter = new AtomicLong();
// inside each pool task:
counter.incrementAndGet();

incrementAndGet() uses a compare-and-swap loop in hardware. If two threads race, one CAS fails and retries with the fresh value, so no update is lost. Correct, and fine for low to moderate contention. Under heavy contention on a single hot counter, every thread hammers the same cache line and throughput collapses. That is the point where LongAdder helps, since it spreads increments across cells and sums them on read.

Fix 2: partition, then reduce (what I would do with a pool)

Java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

ExecutorService pool = Executors.newFixedThreadPool(8);
List<Future<Long>> futures = new ArrayList<>();

for (int t = 0; t < 8; t++) {
    futures.add(pool.submit(() -> {
        long local = 0;
        for (int i = 0; i < 1_000_000; i++) local++;
        return local; // no shared state touched in the loop
    }));
}

long total = 0;
for (Future<Long> f : futures) total += f.get();
pool.shutdown();

Each task owns a plain local variable. No locks, no atomics, no cache line bouncing in the hot loop. The merge happens once, on one thread, after get() establishes the happens-before edge that makes each partial result visible. Total is exactly 8,000,000 every run.

The trade-off is that this only works when the work decomposes into independent partial results, which counting does. If tasks genuinely need to observe each other's increments, for example a quota check that must see the global total, partitioning is wrong and I would go back to AtomicLong or a lock, accepting the contention cost.

How I would verify it

Run the naive version with 8 threads and 1,000,000 increments each, print the result ten times. It will be short by a different amount each time. Then run the partitioned version and the AtomicLong version. Both print 8,000,000 every time. I would also add a stress run under -Xmx pressure and with the pool sized above core count, because oversubscription is where lost updates get frequent enough to see in a single run instead of needing thousands of iterations.

Curated: · Written: · Reviewed:

Difficulty: Medium
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 would treat timeout, retry and circuit breaking as one budget, not three independent settings. The caller has a deadline from its own request, say 800 ms end to end. It passes the remaining time downstream on every attempt, retries only inside that budget, and stops calling a downstream that is already failing so its threads and connection pool stay available for healthy paths.

Concrete defaults I would start from for a non-critical read, for example checking price or stock before showing an offer:

LayerSettingWhy
Connect timeout100 msA host that cannot accept a TCP connection will not recover in 800 ms
Read timeout per attempt300 msBased on downstream p99 of 180 ms at normal load, with headroom
Overall deadline800 msSet by the caller, propagated as X-Request-Deadline
Retries2 retries, 3 attempts maxOnly while deadline remains
Backoff100 ms base, doubling, full jitter, cap 1 sSpreads retries instead of synchronising them
Circuit breakerOpen at 50% failures in a rolling window of 20 calls, half-open after 30 sStops the retry storm
Retry budgetRetries capped at 10% of requests in the last minutePrevents a slow dependency multiplying load

Why the numbers matter

Suppose the caller handles 500 requests per second and has a pool of 200 threads for this call. At a healthy 50 ms downstream latency, it needs about 25 threads. If the downstream slows to 2 s and there is no timeout, 200 threads saturate at only 100 requests per second. The queue grows, latency for unrelated endpoints sharing the pool climbs, and the service looks down even though its own code is fine.

With a 300 ms read timeout, a blocked thread is released six times faster. The caller can still shed load, but it does so with a fast 503 and a Retry-After header instead of holding threads until clients give up. That distinction is what keeps the caller healthy.

Retry policy in code

YAML
# Resilience4j, Spring Boot 3
resilience4j:
  retry:
    instances:
      pricing:
        maxAttempts: 3
        waitDurationInMillis: 100
        exponentialBackoffMultiplier: 2
        maxInterval: 1000
        enableExponentialBackoff: true
        retryExceptions:
          - java.io.IOException
          - java.util.concurrent.TimeoutException
        # 4xx never retried: the request itself is wrong
  circuitbreaker:
    instances:
      pricing:
        slidingWindowSize: 20
        failureRateThreshold: 50
        waitDurationInOpenState: 30000
        permittedNumberOfCallsInHalfOpenState: 3
  timelimiter:
    instances:
      pricing:
        timeoutDuration: 800ms

Two rules sit above that config. First, retry only idempotent operations. GET, PUT and DELETE are safe by HTTP semantics. A POST is retried only when it carries an Idempotency-Key the downstream stores and replays, as with order creation. Without that key, a retry after a timeout can create two orders or two payments, and the timeout tells you nothing about whether the first attempt committed.

Second, jitter is not optional. If 500 callers all fail at 300 ms and retry after a fixed 100 ms, they arrive together at 400 ms and hit the downstream as a second wave at four times the original rate. Full jitter, where the wait is random between 0 and the capped backoff, spreads that wave. The retry budget then caps the damage if jitter is not enough: a token bucket that allows retries equal to 10% of successful requests in the previous minute. When the budget is empty, the caller fails fast.

A worked trace

0 ms    Caller receives request, deadline = 800 ms, forwards remaining budget
0 ms    Attempt 1 to pricing service
300 ms  Read timeout, no response. Backoff sampled: 47 ms
347 ms  Attempt 2, remaining budget 453 ms, per-attempt timeout min(300, 453)
647 ms  Read timeout again. Next backoff would exceed deadline, so stop
647 ms  Caller returns 503 upstream_unavailable to its client, breaker records 2 failures

Note what did not happen. The caller did not start a third attempt that would finish after its own client had already timed out, and it did not retry a 400 or 404. Those responses mean the downstream answered and rejected the request. Retrying them wastes capacity and can turn a client bug into load.

Failure modes I would watch

Timeouts set from a guess drift as the downstream changes, so I would derive the 300 ms figure from a rolling p99 plus headroom and alert when timeout rate exceeds 1% of calls over 5 minutes. A breaker that never opens during a partial slowdown is also a risk: if latency rises but errors stay below 50%, threads still saturate. That is why the bulkhead matters. I would give this dependency its own connection pool and thread pool, sized at 20 connections, so a pricing slowdown cannot consume the 200 threads used by checkout. When that pool is full, new calls fail fast instead of queueing behind slow ones.

Hedging, sending a second request after 150 ms and taking the first answer, is the alternative I would avoid here. It cuts tail latency for reads, but it doubles load precisely when the downstream is struggling, which is the opposite of what a slowdown needs. I would reserve hedging for a downstream with proven spare capacity and a strict latency target, and only with the same retry budget counting hedged requests against it.

The check that this works is simple in production: during a downstream slowdown, the caller's p99 for unrelated endpoints stays flat, its retry ratio stays under the 10% budget, and the breaker opens within one window instead of the caller melting down with it.

Curated: · Written: · Reviewed:

Difficulty: Hard
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 not start by writing tests. I would read the class and ask what it promises: does it mutate the cart, does it return a new total, in what currency, and in what order do discounts apply. Most discount bugs I have seen are not arithmetic errors. They are unspecified precedence and rounding.

Assume a Java service at Allegro scale, cart total in PLN minor units, promotions from a database. I would test the contract first, then the money, then the combinations.

Java
// Checked against Java 21, JUnit 5
@ParameterizedTest
@CsvSource({
  "0,       0,     0",      // empty cart
  "9999,    1000,  8999",   // 10% off 99.99 PLN
  "10000,   1000,  9000",   // threshold exactly met
  "9999,    0,     9999"    // threshold missed by 1 grosz
})
void percentageDiscount(long subtotalMinor, long expectedDiscount, long expectedTotal) {
    var cart = Cart.of(Item.of("p1", 1, subtotalMinor));
    var result = new DiscountService().apply(cart, Discount.percent(10, 10000));
    assertEquals(expectedDiscount, result.discountMinor());
    assertEquals(expectedTotal, result.totalMinor());
}

That table is the core. Boundary at the threshold, empty cart, and a case where rounding decides the result.

Tests I would write

  1. Single discount, exact arithmetic. Fixed amount, percentage, buy-one-get-one, free shipping as a discount line. Each with subtotal below, at, and above its threshold. Thresholds in code are usually > when the business said >=, and only a boundary test catches it.

  2. Rounding and currency. Money as long minor units or BigDecimal with scale 2, never double. Test 33.33 PLN at 10% three times. Per-line rounding gives 3.33 + 3.33 + 3.33 = 9.99 PLN discount. Rounding once on the total gives 10.00 PLN. One grosz difference, and at Allegro volume that is a reconciliation problem with payments and VAT. The test pins which rule the class implements, so a later refactor cannot silently change it.

  3. Stacking and precedence. Percentage then fixed, fixed then percentage, two percentage codes, a code that excludes sale items. If order matters, the test states the order. Example trace: subtotal 200.00 PLN, 10% code, then 20 PLN fixed code. Percentage first: 200 - 20 - 20 = 160. Fixed first: (200 - 20) * 0.9 = 162. Same inputs, 2 PLN apart. If the class iterates a HashSet of promotions, that trace is nondeterministic and the test with both codes will flake or pass by luck.

  4. Invalid and hostile input. Negative quantity, negative price, discount larger than subtotal, expired code, code for another currency, duplicate code in the request. Expected behaviour: total never goes below zero, invalid code is rejected with a typed error, not silently ignored. A silent ignore turns a customer complaint into a support ticket with no log line.

  5. Purity and repeatability. Apply the same discount twice to the same cart object. If the first call mutates line prices, the second call discounts the already discounted price. Test asserts the input cart is unchanged and two calls return equal results. This also covers thread safety if the service is a singleton: no shared mutable fields between calls.

  6. Interaction with tax and shipping. Discount before VAT calculation or after, shipping threshold evaluated on pre-discount or post-discount subtotal. A cart at 100.00 PLN with a 10 PLN discount and free shipping over 95 PLN either ships free or charges 4.99 PLN depending on that choice. Test both, and name the rule in the test.

I would keep these as unit tests with the promotion repository faked. One integration test against a real database for the promotion lookup, because expiry and active flag logic is where SQL BETWEEN on dates goes wrong. No test needs a running checkout.

What I would comment on in review

First, the type of money. double total = price * 0.9 in a cart class is a blocking comment. It will produce 89.99100000001 style results and it cannot represent 0.10 exactly. Ask for minor units or BigDecimal and a single rounding policy at the boundary.

Second, hidden mutation. A method called applyDiscounts(Cart cart) that changes line prices in place makes every caller depend on call order. I would ask for a result object, DiscountedCart or Totals, and leave the input untouched. That one change removes a whole class of double-discount bugs.

Third, magic numbers and scattered rules. if (total > 100) total -= 10; buried in the middle of a method tells me nothing about whether 100 is PLN, whether it is pre-tax, or which promotion owns it. I would ask for named constants or a Promotion value object with thresholdMinor, value, validFrom, validTo, and exclusions, so the test data and the production code read the same way.

Fourth, unspecified precedence. If the class loops over promotions from a list, I would ask who sorts them and what happens on a tie. Without an explicit priority field and a deterministic tie-breaker, adding a new campaign can change the price of an existing one. That is a production incident waiting for the next marketing launch.

Fifth, failure handling. Does an unknown code throw, return empty, or log and continue. I would ask for a typed result the API layer can map to a 422 with a code the client can show, rather than a generic exception that becomes a 500.

I would not comment on formatting or variable names unless they hide the logic. The review goal here is to make the discount rules explicit enough that a test can pin them down. Once precedence, rounding, and mutation are stated, the tests write themselves and the next engineer can change a rule without guessing what else breaks.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10Design a service that shows sellers on a marketplace their live order counts. Cover scalability, performance, monitoring, stability and security?

Reported in Allegro Interview: Devskiller Test, Rounds, Pay

The 90-second answer

First I would pin down what "live order count" means, because the design changes with it. I will assume a seller dashboard shows, for the signed-in seller only, orders placed in the last 24 hours that are paid and not cancelled, refreshed within a couple of seconds. If the business wants all statuses, I keep separate counters per status instead of one number.

The write path is event driven. The order service publishes order.created, order.paid and order.cancelled to Kafka. A stateless consumer updates a Redis counter per seller, keyed by seller and status, and publishes the new value to a push channel. The read path is a thin API plus Server-Sent Events: GET /sellers/me/order-counts for the initial snapshot, then a stream that pushes deltas. Redis holds the hot counters, Postgres holds the source of truth, and a reconciliation job repairs drift.

Order service --Kafka--> Counter consumer --INCR--> Redis (seller counters)
                              |                         |
                              +-- publish delta --------+
Seller browser <--SSE/HTTPS-- API (auth, tenant check) --MGET--> Redis
                              |
                              +-- fallback: Postgres aggregate (stale, labelled)

Ingestion and correctness

Kafka gives me ordering per partition if I partition by seller_id, which matters because a paid event must not be applied before the created event for the same seller. The consumer is idempotent: it stores the last processed event_id per seller in Redis, or uses a Lua script that checks and increments atomically, so a redelivery after a crash does not double count.

Java
// Consumer, Java 21, checked against Kafka clients 3.x semantics
long applied = redis.eval(
  "if redis.call('SISMEMBER', KEYS[1], ARGV[1]) == 1 then return 0 end " +
  "redis.call('SADD', KEYS[1], ARGV[1]) " +
  "redis.call('INCRBY', KEYS[2], ARGV[2]) return 1",
  List.of("seen:" + sellerId, "count:" + sellerId + ":paid"),
  List.of(eventId, "1"));

That seen set grows unbounded, so I expire it after 48 hours and keep the reconciliation job as the backstop. Counters are daily buckets (count:{sellerId}:paid:2026-05-13) so a 24 hour window is a sum of two keys, and old buckets expire on their own. No unbounded key growth, no expensive scans.

Scale, with numbers

Hypothetical peak for a large marketplace sale event: 20,000 orders per minute across the platform, 30,000 sellers active in that minute, and 200,000 sellers polling or streaming at once. That is about 333 writes per second to Redis, trivial for one Redis shard, and about 3,300 reads per second for polling. The push fan-out is the real cost: 200,000 concurrent SSE connections at roughly 8 KB of server memory each is about 1.6 GB plus file descriptors, so I spread connections across API instances behind a load balancer and let each instance own a slice of sellers. If polling alone would be 200,000 sellers refreshing every 5 seconds, that is 40,000 requests per second, which is why push replaces polling for the live view and the REST call is only the snapshot on connect.

Redis Cluster with seller_id hash tags keeps a seller's keys on one slot, so the Lua script stays single slot. If a shard saturates, I add shards; counters are independent per seller, so resharding does not need cross seller coordination.

Failure modes and stability

The failure I design around is drift: a consumer dies mid batch, an event is lost, or Redis evicts a key. Detection is a lag metric on the Kafka consumer group and a hourly reconciliation that recomputes counts from Postgres for a sample of sellers and compares. If drift exceeds a threshold, say 0.1% of sellers sampled, I page and rebuild the affected buckets from Postgres rather than trusting the counter.

If Redis is unavailable, the API does not return an error to the seller. It falls back to a Postgres aggregate query over the orders table, which is slower (I would budget p99 around 300 ms for a single seller with an index on (seller_id, created_at, status)) and returns a stale: true flag with the timestamp, so the UI can show "updated 4 minutes ago" instead of a confident wrong number. Circuit breakers on the Redis client stop a Redis outage from exhausting API threads.

Monitoring

SignalWhat it catchesAlert threshold (hypothetical SLO)
Kafka consumer lag per partitioningestion falling behindlag > 10 s for 5 min
Counter freshness: now minus last event time per sellersilent event lossp95 staleness > 5 s
Redis memory and evictionshot keys being droppedevictions > 0
API p99 and SSE disconnect rateoverloaded read pathp99 > 200 ms for snapshot
Reconciliation drift ratedouble counting or lost events> 0.1% of sampled sellers

I would also track per seller write volume, because one large seller running a promotion can be 100 times the median, and that shows up as a hot Redis slot before it shows up as a platform incident.

Security

The seller identity comes from the session or OAuth token, never from a query parameter. The API resolves the seller from the principal and ignores any seller_id the client sends, which closes the obvious IDOR where seller A reads seller B's counts by changing an ID in the URL. SSE connections are authenticated the same way and rechecked on reconnect. I rate limit the snapshot endpoint per seller, for example 60 requests per minute, because order counts are commercially sensitive and easy to scrape across many accounts. Counts are aggregated data, so no buyer personal data touches this service at all, which keeps it out of the strictest data handling rules. Every admin rebuild of a counter is audit logged with who triggered it and which seller range was affected.

The trade off I would name in the room: exactness versus freshness. A database query per refresh is exact and simple, and it collapses at marketplace peak. The counter design is fast and cheap at peak, and it needs the reconciliation job and the stale flag to stay honest. I would ship the counter design only with both of those in place.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11Design chat on an e-commerce page?

Reported in What to Expect in the Allegro System Design Interview

The 90-second answer

I would clarify the chat type first, because it changes the routing and the data model. On an Allegro product page that is usually one of two things: buyer to Allegro support about delivery or a return, or buyer to seller about the listing. I will design for both on one conversation service, with the product, offer and, when it exists, the order attached to the thread. That context is what makes the chat useful. An agent or seller does not ask the buyer for the order number they already have.

The core path is: browser opens a WebSocket to a gateway, the gateway authenticates the session, publishes the message to a queue, a chat service writes it once with a server assigned sequence number, and a fan-out service pushes it to the other participant if they are online. If they are offline, the message waits in the inbox and they fetch it on reconnect. Storage is append only. You never update a message in place, you append an edit or a delete marker, which keeps the audit trail for disputes.

Buyer browser --WSS--> Gateway (auth, presence) --Kafka--> Chat service --> Cassandra
                              |                              |
                              +---- presence store ----------+--> push to online peer
                              +---- offline inbox (Postgres) --> fetch on reconnect
Agent/seller console --WSS--> Gateway

Scale I am designing for, labelled as assumptions

Say 50,000 concurrent WebSocket connections at peak, 300 messages per second sustained and 1,500 per second in a flash sale spike, average thread of 12 messages. That is roughly 26 million messages a day at peak. A gateway node holding 20,000 idle connections is realistic if you keep per-connection state small and move everything else out. Presence is the expensive part, not the message write.

TransportWhy I would or would not use it
WebSocketBidirectional, typing indicators and read receipts come free. Needs sticky routing or a pub/sub layer between gateways, plus a heartbeat to reap dead connections.
Server-Sent EventsSimpler, auto reconnects, one way only. Fine for buyer receiving messages, awkward for typing and presence from the client.
Short pollingWorks everywhere, but at 50,000 users polling every 5 seconds is 10,000 requests per second of mostly empty responses. I would only use it as a fallback.

Ordering, duplicates and the reconnect trace

Ordering matters more than raw speed here. A buyer sends "cancel it" and then "please, before dispatch". If those arrive reversed, the seller acts on the wrong instruction. So the client sends a client_msg_id (a UUID generated in the browser) and the server assigns seq per conversation, monotonically increasing, at write time. The client renders by seq, not by arrival time.

Trace for a flaky mobile connection:

  1. Buyer sends client_msg_id=9c1e..., text "Where is my parcel?", server writes it as seq=41, returns an ack with seq=41.
  2. The ack is lost. The buyer reconnects and replays the same client_msg_id.
  3. The chat service finds client_msg_id already stored for that conversation and returns the original seq=41 instead of inserting a duplicate.
  4. On reconnect the client also sends last_seen_seq=38. The server returns messages 39 to 41 in order, then resumes live delivery.

That one mechanism, idempotent send plus a per-conversation sequence, covers duplicates, reconnects and ordering without distributed locks.

Data model

SQL
-- Cassandra, one partition per conversation, clustered by seq
CREATE TABLE messages (
  conversation_id uuid,
  seq bigint,
  client_msg_id uuid,
  sender_id uuid,
  body text,
  created_at timestamp,
  PRIMARY KEY (conversation_id, seq)
);

A separate small table holds conversation metadata: participants, product_id, offer_id, order_id, status (open, pending, closed), and the last seq. Metadata goes in Postgres because agents query it by seller, status and SLA. Messages go in Cassandra because the access pattern is always "give me this thread in order" and writes are append only. If I had to pick one store for a first version, Postgres with a composite index on (conversation_id, seq) would carry this load, and I would move messages out when write volume or retention cost forced it.

Failure modes I would name in the interview

Presence lies. A WebSocket that half closed looks online for minutes. I would expire presence after 45 seconds without a heartbeat and treat presence as a hint, never as proof of delivery. Delivery is proven by the ack and by the inbox fetch.

Agent overload. A seller with 400 open threads will miss messages. I would cap concurrent threads per agent, queue new conversations by category (delivery, return, product question), and show queue position to the buyer instead of a silent spinner. When the queue exceeds a threshold, offer asynchronous mode: the buyer leaves a message and gets a notification when it is answered.

Abuse and privacy. Chat on a marketplace gets phone numbers, links to off-platform payment, and personal data. I would scan outbound messages for contact details and payment links before delivery, rate limit new threads per account, and keep message bodies encrypted at rest with access logged. Retention needs a decision up front: support threads kept for dispute handling, seller threads kept shorter, and a deletion job that removes bodies but keeps metadata for accounting. Under GDPR that retention schedule and the legal basis for keeping it have to be written down, not improvised.

What I would build first

One conversation type, buyer to support, with product and order context attached, WebSocket delivery, idempotent send, per-conversation ordering, and an offline inbox. Seller chat reuses the same service with a different routing rule and a different retention policy. I would not add voice, video or AI triage until the text path holds its ordering and delivery guarantees under load, because those features multiply the failure modes without fixing the core one.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12Design 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 and a read path, because publishing is rare and bursty while searching is frequent and latency sensitive. On the write path, a seller submits an offer through an API, we validate and persist it as the source of truth, then publish a change event. An indexer consumes that event and writes a denormalised document into the search index. On the read path, a buyer query hits a search service that queries that index, applies filters and ranking, and returns offer IDs that the listing service hydrates with live price and stock. The buyer never reads the transactional database for search.

Seller app -> Offer API -> Offer DB (source of truth)
                    |-> Outbox / Kafka: offer.published.v1
                    |-> Moderation / category check (async gate)
                    v
              Indexer -> Search index (OpenSearch)
Buyer -> Search API -> Search index -> Ranking -> Listing API -> Price/Stock

Write path, step by step

POST /offers with an Idempotency-Key creates the offer in DRAFT. The API validates the seller account, category, mandatory attributes for that category, price range and delivery settings. Polish marketplace categories matter here: a phone offer without a model attribute will rank badly and convert badly, so we reject incomplete offers at publish time rather than fixing them in search.

On publish, the API transitions the offer to PENDING_REVIEW or directly to ACTIVE depending on seller trust tier, writes the row and an outbox row in the same transaction, and returns 202 with the offer ID. The outbox relay publishes to Kafka. That avoids the classic dual-write bug where the DB commits and the event is lost, or the event fires and the DB rolls back.

The indexer consumes offer.published.v1, builds a search document, and upserts it by offer_id. The document is denormalised on purpose: title, category path, brand, attributes, price, seller rating, delivery options and a Polish stemmed text field. If the indexer had to join five tables at query time, p99 would blow up and a slow product table would take down search.

Trace for one publish:

10:00:01.120  POST /offers  Idempotency-Key: a91f  -> 201 offer_id=884120 status=DRAFT
10:00:01.180  POST /offers/884120/publish -> 202 status=PENDING_REVIEW
10:00:01.190  Outbox relay -> Kafka offer.published.v1 (offset 441209)
10:00:01.340  Indexer upserts doc 884120 into index offers_v42
10:00:01.350  Search for "laptop lenovo" now returns 884120 (rank depends on relevance)

If moderation is required, the indexer writes the document with visible=false and a second event flips it to visible=true. Search filters on visible=true, so a rejected offer never leaks into results even if it was indexed early.

Read path

GET /search?q=laptop+lenovo&category=electronics&price_max=3000 goes to the search service. It parses the query, applies Polish stemming and typo tolerance, builds a filter query for category, price and availability, and asks the index for the top N candidates, say 200. Ranking then reorders those candidates using signals the index alone should not own: seller rating, conversion rate, delivery speed, personalisation and sponsored placement rules. The search service returns offer IDs plus rank positions. The listing service hydrates the first page, typically 48 items, with current price and stock from the pricing and inventory services.

That hydration step is where stale data gets caught. The index might say an offer costs 2,999 PLN, but if stock hit zero 30 seconds ago, the listing service drops it or marks it unavailable before the buyer sees it. Search stays fast because it does not call inventory for every candidate, only for the page the buyer actually sees.

ConcernWrite path choiceRead path choice
Source of truthOffer DB, transactionalSearch index, eventually consistent
Freshness targetPublish acknowledged in under 1 sSearchable within 2 to 5 s, labelled as such
Price and stock changesSeparate high-frequency events, offer.price_changed.v1Hydrate page from live services, do not trust index price
Deletionoffer.withdrawn.v1 tombstone eventFilter status=ACTIVE, plus hydration check
Scale assumptionThousands of publishes per minute at peak salesTens of thousands of searches per second, p99 under 200 ms

Failure modes I would name in the interview

Index lag during a promotion. If 50,000 sellers edit offers in an hour, the indexer queue backs up and buyers see old prices. Detection: consumer lag on the Kafka topic and a freshness metric per shard. Mitigation: partition by offer_id, scale indexers horizontally, and prioritise price and withdrawal events over title edits.

Duplicate or out-of-order events. A seller edits a title twice quickly and the older event arrives last. The indexer upserts by offer_id and version, and ignores any event whose version is lower than the document already stored. Without that check, search would silently revert to stale text.

Withdrawn offer still searchable. The tombstone event is lost or delayed. The hydration check is the safety net, but it only covers the first page. I would also run a periodic reconciler that compares active offer IDs from the DB against the index in batches and deletes orphans.

Bad document, good offer. A category mapping change makes attributes land in the wrong field and the offer becomes unfindable for its main query. Detection: a canary query set per top category, run after every index template or mapping deploy, checking that known offers still rank for their expected terms.

What I would not do

I would not query the offer DB with LIKE '%laptop%' for buyer search. It cannot handle Polish morphology, typo tolerance, faceted filtering or ranking, and it couples search load to the transactional store. I also would not make publishing synchronous with indexing. If the search cluster is slow, sellers should still be able to publish and see their offer in their own dashboard, with search catching up seconds later.

Follow-up I expect: how to handle personalised ranking and sponsored offers without polluting the index, and how to reindex when the mapping changes. For a mapping change I would build a new index version, backfill from the DB in parallel, alias the search service over once canary queries pass, and keep the old index for rollback.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13Design a conversation between a buyer and a seller, attached to one offer or one order?

Reported in What to Expect in the Allegro System Design Interview

The 90-second answer

I would scope the conversation to the transaction, not to the users. A buyer and a seller can have many threads, but each thread belongs to exactly one offer before purchase or one order after purchase. That scoping gives me permissions, retention and moderation for free: only the two parties on that order can read it, and the thread closes when the order closes.

I would allow one pre-order thread per buyer per offer for questions about condition, delivery or price, and then create a fresh order thread at checkout. I would not reuse the offer thread for order disputes, because the order thread needs order state, payment references and a different retention clock. If a buyer asks a question on an offer and then buys, the seller sees both, but they stay separate records.

Data model

SQL
-- Postgres, checked against Postgres 16
CREATE TABLE conversation (
  id            BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  offer_id      BIGINT NOT NULL,
  order_id      BIGINT,               -- NULL until checkout
  buyer_id      BIGINT NOT NULL,
  seller_id     BIGINT NOT NULL,
  status        TEXT NOT NULL,        -- OPEN, CLOSED
  last_seq      BIGINT NOT NULL DEFAULT 0,
  last_msg_at   TIMESTAMPTZ NOT NULL,
  created_at    TIMESTAMPTZ NOT NULL DEFAULT now(),
  UNIQUE (offer_id, buyer_id, seller_id, order_id)
);

CREATE TABLE message (
  conversation_id BIGINT NOT NULL REFERENCES conversation(id),
  seq             BIGINT NOT NULL,    -- per-conversation sequence
  sender_id       BIGINT NOT NULL,
  body            TEXT NOT NULL,
  attachment_id   BIGINT,
  client_msg_id   UUID NOT NULL,      -- idempotency key from the client
  created_at      TIMESTAMPTZ NOT NULL DEFAULT now(),
  PRIMARY KEY (conversation_id, seq),
  UNIQUE (conversation_id, client_msg_id)
);

seq is allocated inside the conversation row with UPDATE conversation SET last_seq = last_seq + 1 RETURNING last_seq in the same transaction as the insert. That gives a total order per thread without a global counter. At Allegro scale I would partition message by conversation_id range and keep the hot inbox list in a separate table keyed by (user_id, last_msg_at DESC) so listing a mailbox never scans messages.

API

OperationEndpointContract detail
find or createPOST /conversations with offer_idreturns existing thread if the unique key matches
sendPOST /conversations/{id}/messagesIdempotency-Key: <uuid> required, returns 201 with seq
list messagesGET /conversations/{id}/messages?after_seq=120&limit=50keyset on seq, never offset
inboxGET /me/conversations?cursor=...&limit=30cursor on (last_msg_at, id)
mark readPOST /conversations/{id}/read with up_to_seqmonotonic, a lower value is a no-op
closePOST /conversations/{id}/closeallowed when the order is delivered or cancelled

Permissions are checked against the conversation row on every call. A seller who is not seller_id on that row gets 403, even if they know the id. I would not put user ids in the path and trust them.

Worked trace: a retry and an out-of-order arrival

Hypothetical load for sizing: 2 million messages a day, peak 400 writes a second, average body 180 bytes. That is about 360 MB of body text a day before attachments, which fits comfortably in partitioned Postgres if I archive closed conversations older than 90 days to object storage and keep only metadata online.

  1. Buyer sends "Is the charger included?" with client_msg_id = 9b1.... The server locks the conversation row, allocates seq = 41, inserts the message, commits, returns 201 seq=41.
  2. The client times out and retries with the same key. The unique constraint on (conversation_id, client_msg_id) fires, the server reads back seq=41 and returns the original 201. No duplicate appears.
  3. The seller replies at the same moment. Their transaction waits on the row lock, gets seq=42, commits. Ordering is by seq, not by client timestamps, so clock skew on phones never reorders the thread.
  4. The buyer is offline. The send still commits. A notification job reads the inbox table, sends a push with conversation_id and seq=42, and the client fetches after_seq=41 when it reconnects. If the push is lost, the unread badge is recomputed from last_seq minus the stored read_seq, so it self-corrects.

Failure modes I would name in the interview

Duplicate sends from double taps and retries are handled by the idempotency key above. A race to create the same offer thread twice is handled by the unique key plus a SELECT on conflict, returning the winner. Attachments go to object storage first, the message stores only the attachment id, and a message with a missing attachment renders as a placeholder rather than failing the whole list call. For abuse, I would rate limit sends per conversation (for example 30 a minute) and per user, and route flagged messages to moderation with the conversation context attached, since a message without its offer or order is hard to judge. Deleted offers and GDPR erasure are the awkward case: I would keep the conversation row and message bodies for the statutory retention period for order disputes, anonymise buyer_id and seller_id after that, and drop attachment bytes earlier. That trade-off is worth stating explicitly, because a pure chat design would delete everything on request and break dispute evidence.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14Design 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 not try to make the network deliver exactly once. I would make every retry land on the same stored intent, and make the database reject a second charge for that intent. The client generates an Idempotency-Key for one checkout attempt, the order service stores it under a unique constraint before it calls the payment gateway, and the gateway call reuses that same key. A retry then returns the original order instead of creating a new payment.

Assumptions I would state up front: one order, one payment attempt per checkout click, the gateway (for example Stripe, Adyen, or an internal PSP) supports idempotency keys and a status lookup by key, and we can keep the key for at least 24 hours. If the gateway did not support that, I would need a reconciliation job as the safety net, not as the primary mechanism.

Client -> API Gateway -> Order Service -> Postgres
                              |              |
                              |              +-> Payment Gateway (same key)
                              +-> Outbox -> Kafka / PSP webhook consumer

The flow

  1. Client creates a checkout session and generates Idempotency-Key: 9c4e-... (UUID v4). It reuses that key for every retry of that click. A new click for a new purchase gets a new key.
  2. POST /orders runs in one transaction: insert the order in CREATED, insert a payment_intents row with idempotency_key unique and status PENDING, insert an outbox event. If the unique constraint fires, the transaction rolls back and we load the existing order by key.
  3. After commit, a worker (or the request thread, if latency allows) calls the gateway with Idempotency-Key: 9c4e-... and our payment_intent_id as the gateway reference. It stores the gateway charge id and moves the intent to CHARGED or FAILED.
  4. The response to the client is the order id plus payment status. A retry with the same key returns that same response, even if the first response was lost.
SQL
CREATE TABLE payment_intents (
  id UUID PRIMARY KEY,
  order_id UUID NOT NULL REFERENCES orders(id),
  idempotency_key TEXT NOT NULL UNIQUE,
  request_hash TEXT NOT NULL,  -- hash of amount, currency, order_id
  status TEXT NOT NULL,        -- PENDING, CHARGED, FAILED, UNKNOWN
  gateway_charge_id TEXT,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

The request_hash matters. If a client reuses a key with a different amount, that is a bug or an attack, not a retry. I return 422 with idempotency_key_reused instead of replaying the old charge.

Worked trace

TimeEventResult
t=0POST /orders key 9c4e, 249.00 PLNInsert succeeds, gateway call starts
t=300msGateway charges, returns ch_123Intent CHARGED, order PAID
t=400msResponse lost on the networkClient sees a timeout, does not know the outcome
t=900msRetry, same key 9c4e, same bodyUnique lookup hits, no gateway call, returns order 42, PAID, ch_123
t=950msClient shows confirmation onceOne charge, one order

The harder case is a crash between the gateway charge and our database update. The intent stays PENDING or moves to UNKNOWN on timeout. A reconciliation job then queries the gateway by idempotency key every few minutes for intents older than, say, 5 minutes. If the gateway has a charge, we mark CHARGED and emit the outbox event. If it has none, we can safely retry the gateway call with the same key. That job is what turns "we think it charged" into a provable state.

Failure modes I would name in the interview

Timeout after charge: handled above, by key lookup plus reconciliation. Never create a new key to "try again", that is how double charges happen.

Two concurrent retries racing: both try to insert the same key. Postgres unique constraint serialises them. One wins, the other gets the existing row. No application-level lock needed, and no check-then-insert race.

Gateway timeout with no charge: intent stays PENDING, reconciliation confirms absence, then a retry with the same key is safe because the gateway deduplicates on it.

Key expiry: I keep keys for 72 hours for payments, longer than the 24 hours typical for a plain order create, because a customer can retry from a restored browser session. Storage is small. At 500k checkouts a day, 72 hours is 1.5M rows. At roughly 200 bytes per row plus index, that is under 1 GB, so retention is not the constraint. Correctness is.

Webhook arriving before the synchronous response: the webhook handler updates the same payment_intents row by gateway_charge_id and is itself idempotent. It checks current status and only transitions PENDING -> CHARGED, never CHARGED -> CHARGED as a new event.

What I would not do

I would not rely on a distributed lock or a Redis key as the source of truth for "already charged". Locks expire, Redis can evict, and neither survives a restore from backup. The Postgres unique constraint is the arbiter. Redis can cache the lookup to save a database read, but the database decides.

I would also not put the gateway call inside the database transaction. That holds a connection open for the gateway latency (often 200 to 800 ms) and, worse, a rollback after a successful charge would leave a real charge with no local record. Commit the intent first, call the gateway second, reconcile third.

If the interviewer pushes on refunds or partial payments, the same pattern extends: each refund gets its own idempotency key tied to the original charge id, and the order state machine only allows PAID -> REFUNDED once. The principle stays the same. One key, one intent, one stored outcome, replayed on retry.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15Design 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 two services with different jobs. A promise service decides the date shown at checkout. A tracking service keeps that date honest as the parcel moves. They share one event stream and one definition of accuracy, otherwise the checkout number and the tracking number drift apart.

At checkout I do not ask a carrier API in real time. I precompute, for each seller or warehouse, carrier, destination zone and order cutoff, a delivery estimate from history. The promise stored on the order is a date, a confidence band and the inputs used. When a scan arrives, the tracking service recomputes the remaining time from the current location and the carrier's remaining leg, and only changes the buyer-facing date if the new estimate crosses a threshold. That threshold matters. Updating on every scan trains buyers to ignore the date.

What the promise is computed from

InputExampleWhy it moves the date
Seller handling time24 h median, 48 h p90Dispatch is the first leg, and it is the one we control least
Cutoff timeOrders after 16:00 ship next working dayA 15:59 order and a 16:01 order are different promises
Warehouse to destination zoneWarsaw to Krakow 1 day, Warsaw to Gdansk 2 daysDistance and carrier network, not straight line distance
Carrier service levelStandard 2-3 days, express next daySame parcel, different promise
CalendarWeekends, Polish public holidays, carrier holidaysA Friday dispatch on a 2 working day service lands Tuesday

For a lane I keep the empirical distribution, not just an average. Say 10,000 recent parcels on Warsaw to Krakow standard: 62% delivered in 1 day, 88% in 2 days, 97% in 3 days. Promising day 2 gives a 12% miss rate. Promising day 3 gives 3% but costs conversion. That trade-off is a product decision, so the service returns the percentile it used, for example p88, and the accuracy dashboard reports against that same percentile. If I promise p88 and only 80% arrive on time, the model or the inputs are wrong, not the definition.

A worked trace. Order placed Tuesday 15:40 in Krakow, seller in Warsaw, handling p90 24 h, cutoff 16:00, standard carrier.

Tue 15:40  order placed, before cutoff, dispatch Wed
Wed 09:12  seller scan, parcel with carrier, hub Warsaw
Wed 18:30  hub scan, departed Warsaw, remaining leg p88 = 1 day
Thu 11:05  out for delivery in Krakow, promise Thu holds
Thu 13:20  delivered, promise kept, actual vs promised recorded

If the Wednesday hub scan is missing, the service does not assume the parcel is still with the seller. It falls back to elapsed time since dispatch plus the lane distribution for parcels with no hub scan, which is wider. The band widens, the date stays, and the internal flag confidence=low is set. That is how a missing scan becomes a monitoring alert instead of a wrong date shown to the buyer.

Keeping it accurate after checkout

Events arrive on Kafka: OrderPlaced, ParcelDispatched, HubScan, OutForDelivery, Delivered, DeliveryFailed, AddressChanged. Each event carries parcel id, location, timestamp and carrier. A state machine per parcel applies them in order, with event time not processing time, because carriers batch scans and a scan can arrive hours late.

Java
// checked against Java 21, illustrative core
record Promise(LocalDate date, int percentile, Confidence confidence) {}

Promise recompute(ParcelState state, LaneStats lane) {
    Duration remaining = lane.percentile(state.currentLeg(), 88);
    LocalDate eta = state.lastScanTime().plus(remaining).toLocalDate();
    Confidence c = state.scansSinceDispatch() >= 2 ? Confidence.HIGH : Confidence.LOW;
    return new Promise(eta, 88, c);
}

The buyer sees a new date only when the recomputed date differs from the promised date and the change persists for one more event or a delay window, say 2 hours. A single late hub scan that moves the estimate by a day and then reverses is noise. A carrier delay notice plus a missed hub departure is signal.

Accuracy is measured three ways, by lane and by seller, not as one global number. Promise kept exactly, promise kept within one day, and calibration: of parcels promised at p88, what share actually arrived by that date. A lane at 70% against an 88% promise is miscalibrated even if the global average looks fine, because one bad seller or one carrier depot is hiding inside it.

Failure modes I would name in the interview

Split shipments. One order, two parcels, two dates. The promise is per parcel, and the buyer-facing date is the latest parcel date, with a note that the order ships in parts. Averaging them produces a date that matches neither parcel.

Seller late dispatch. The promise assumed 24 h handling. If dispatch slips past p90, the tracking service recomputes from actual dispatch, not from order time, and the date moves once, early, before the buyer has built plans around the original date.

Carrier scan gaps and duplicate scans. Duplicates are idempotent on carrier scan id. Gaps widen the band as above. A carrier that stops sending scans for a lane triggers an alert on scan volume per lane, because the first symptom is not a wrong date, it is silence.

Address change and failed delivery. Both restart the remaining leg calculation from the new destination or the return leg. A failed delivery attempt is not a delivered parcel, and the promise moves to the next attempt window rather than staying on the original date.

I would not put a machine learning model in the first version. Rules over lane percentiles are explainable to sellers, which matters at Allegro because a seller who sees why a date moved is more likely to fix handling time than one who is shown a black box score. Once the event pipeline and the calibration metrics are in place, a learned model can replace the percentile lookup per lane, and I would compare it on the same calibration metric before it touches a buyer-facing date.

Curated: · Written: · Reviewed:

Difficulty: Hard

Curated: · Written: · Reviewed: