All modules

Messaging and async: interview questions

14 questions. Try answering out loud before you open the model answer.

1. Order events need to reach email, fraud scoring and analytics. Would you use a queue or a log, and why?

Seniorqueueskafkapub-sub

What the interviewer is really testing

Whether you choose a broker by the semantics the use case needs (number of consumers, replay, ordering, per-message handling) and not by brand, and whether you can say what the choice costs.

Show the model answer, follow-ups and checklist

Model answer

I would start from what each consumer needs, because that decides the model.

“Order placed” is a fact that three independent systems care about, and more will follow. That is publish/subscribe: each consumer gets every event, and none of them knows about the others. The producer publishes once, and the question is what sits behind the topic.

I would use a log such as Kafka, keyed by order ID, for three reasons:

  • Independent consumers. Each service is its own consumer group with its own offset. Analytics being down for an hour does not affect email.
  • Replay. Fraud models are retrained and analytics pipelines are rebuilt. With a week or more of retention, a new or repaired consumer can read history. A queue would have deleted it.
  • Ordering per order. Placed, paid and shipped for one order stay in sequence on one partition.

The cost is that a log gives me less control per message. One bad record blocks its partition, so each consumer needs its own retry and dead-letter handling. Consumer parallelism is capped by the partition count. Delivery is at least once, so every consumer must be idempotent on the event ID.

The email consumer is the one that fits a log least well. Sending is a task, with slow and flaky calls to a provider, and it wants per-message retries with delays. I would have a small consumer read the log and put send jobs on a queue such as SQS with a dead-letter queue, so that one stuck email does not hold up the others.

If the team is small, the volume is modest and nobody needs replay, SNS fanning out to one SQS queue per consumer is a sound alternative with far less to operate. I would say so, and choose it if those conditions hold.

Likely follow-ups

A fourth team wants these events next quarter, including the last 30 days of history. What changes?
With a log, nothing changes for the producer. The team creates a new consumer group and starts from the earliest offset, provided retention is at least 30 days, so I would set retention with that kind of request in mind. With SNS and SQS the new queue receives only events published after it subscribes, so the history would need a backfill from the orders database.
Why not have the order service call the three services directly?
Checkout would be as slow and as unreliable as the worst of the three, and every new consumer would mean a code change and a deploy for the order service. A broker lets checkout finish after one durable write and lets each consumer fail and recover independently.
How do you make sure the event is published if the order service crashes just after committing the order?
Use a transactional outbox. The event is inserted into an outbox table in the same database transaction as the order, and a relay publishes it to the log afterwards. The relay can publish twice, which the idempotent consumers already handle.
Fraud scoring must be able to block a risky order. Does it still consume from the log?
Not for the blocking decision. If checkout needs the score before it answers, that is a synchronous call with a timeout and a fallback. The log still feeds fraud's asynchronous work, such as model features and review after the fact.

Common mistakes

  • Naming Kafka immediately without saying which properties of a log the use case needs.
  • Putting all three services on one shared queue, so each event reaches only one of them.
  • Forgetting that consumers will see duplicates and need to be idempotent.
  • Treating the email sender like a stream consumer and ignoring per-message retries and dead-lettering.
  • Not mentioning the simpler managed option when the scale does not justify running Kafka.

A strong answer includes

  • Identifies the pattern as one event going to several independent consumers
  • Chooses by semantics, naming replay, independent offsets and per-key ordering
  • States the partition key and why
  • States the costs: head-of-line blocking, parallelism capped by partitions, at-least-once delivery
  • Separates task-style work (sending email) and gives it a queue with a dead-letter queue
  • Offers SNS plus SQS as the lower-operations alternative and says when it is enough

Revise: Queues vs logs

2. A team wants to run long video transcoding jobs through a Kafka topic. What problems do you expect?

Mid-levelqueueskafkatask-queues

What the interviewer is really testing

Whether you understand the practical differences between a log and a queue for task workloads: no per-message acknowledgement, head-of-line blocking, poll timeouts and parallelism bound to partitions.

Show the model answer, follow-ups and checklist

Model answer

It can be made to work, but Kafka’s consumption model fights this workload in four ways.

Long jobs collide with the poll loop. A consumer must call poll() again within max.poll.interval.ms, which is five minutes by default. A transcode that takes 20 minutes means the consumer is considered dead, its partitions are reassigned, and another worker starts the same video. I can raise the interval, or pause the partition and keep polling while a background thread does the work, but at that point I am writing my own job runner.

There is no per-message acknowledgement. Progress is one offset per partition. If job 10 is slow and jobs 11 to 15 are finished, I cannot commit 15 without also claiming 10. A crash replays everything after the last commit, and a slow or failing job blocks everything behind it on that partition.

Parallelism is tied to partitions. Forty workers need at least forty partitions, and going beyond that means repartitioning. With a queue I just add workers. Every scale-up or scale-down also triggers a rebalance, which hurts when jobs are long.

The extras are missing. Priorities, delayed retries and dead-lettering all have to be built from additional topics.

So for transcoding I would use a queue: SQS with a visibility timeout that a heartbeat extends while the job runs, a maximum receive count, and a dead-letter queue. Workers scale on queue depth.

I would keep Kafka for what it does well here, which is the “video uploaded” event that several systems consume. A small consumer turns that event into a job on the queue.

I would also mention that Kafka 4 introduced share groups, which add queue-style acknowledgement to a topic. I would check how mature they are in the version we run before depending on them.

Likely follow-ups

If they insist on Kafka, how would you make it workable?
Keep the consumer thread polling and do the work elsewhere. Pause the partition, run the job on a worker thread, then resume and commit when it finishes, with one job in flight per partition so the offset stays meaningful. Raise max.poll.interval.ms as a margin, use static membership to avoid rebalances on restarts, and make the transcode idempotent by writing output to a path derived from the video ID.
On the SQS design, a worker dies halfway through a transcode. What happens?
It stops extending the visibility timeout, so the message becomes visible again and another worker receives it. The job restarts from the beginning unless progress was checkpointed, and writing output to a deterministic location makes the repeat harmless. Once the maximum receive count is passed, the message goes to the dead-letter queue.
When is Kafka a reasonable job queue?
When jobs are short and uniform, per-key ordering is useful, throughput is high and you already run Kafka. Plenty of teams process large volumes of small tasks this way. The mismatch grows with job duration and with the need for per-job retries, delays and priorities.

Common mistakes

  • Saying Kafka cannot do it, when the real point is how much you must build around it.
  • Ignoring max.poll.interval.ms and the rebalance that a long job triggers.
  • Assuming offsets can be committed out of order.
  • Proposing more consumers than partitions as a way to scale.
  • Forgetting that a restarted job must be safe to repeat.

A strong answer includes

  • Explains the poll interval problem for long jobs and its consequence: a rebalance and duplicate work
  • Explains that progress is one offset per partition, so a slow job blocks those behind it
  • Notes that parallelism is capped by the partition count
  • Recommends a queue with a visibility timeout, heartbeat extension, receive limit and dead-letter queue
  • Keeps the log for the multi-consumer event and bridges from it to the queue
  • Mentions idempotent job output

Revise: Queues vs logs

3. How would you guarantee that events for the same account are processed in order?

Seniorkafkaorderingpartitioning

What the interviewer is really testing

Whether you know that ordering in a partitioned log is per partition, can choose a key deliberately, and can list the ways ordering still breaks: producer retries, partition changes, consumer concurrency and retry handling.

Show the model answer, follow-ups and checklist

Model answer

Order has to hold at every stage, so I would walk the path: producer, broker, consumer.

Key by account ID. Kafka orders records within a partition only. If the account ID is the record key, every event for that account hashes to the same partition and is stored in the order the broker received it. I do not need global order and should not ask for it, because a single partition would limit the topic to one consumer.

Keep the producer from reordering. If two batches are in flight and the first fails and is retried, it can land after the second. The idempotent producer, which is the default since Kafka 3.0, preserves order across retries with up to five requests in flight. I also need each account’s events to come from one writer, or to carry a sequence number, because two service instances publishing concurrently for one account have no defined order to preserve.

Keep the consumer from reordering. One consumer per partition reads in order, but handing records to a thread pool destroys that. If I need concurrency inside a consumer, I dispatch by key: hash the account ID to one of N single-threaded workers, so that one account is always handled serially.

Decide what a failure does. If an event fails and I send it to a retry topic, later events for that account overtake it. For a ledger that is unacceptable, so I would either block the partition or park later events for that account until the failed one is resolved.

Do not change the partition count casually. Adding partitions changes which partition a key maps to, so new events can be consumed before older ones that are still queued in the old partition.

As a safety net I would put a per-account version number in each event. The consumer stores the last version it applied, ignores anything older and detects gaps. That keeps the consumer correct even when delivery is duplicated or slightly out of order.

Likely follow-ups

One account produces 30% of all traffic. What happens, and what can you do?
Its partition becomes hot and its consumer lags while the others sit idle. You can split the key if order is only needed within a sub-entity, such as account plus wallet, give that tenant a dedicated topic, or make the consumer for that partition faster with batching. You cannot spread a single ordered key over several partitions without giving up its order.
You have to grow the topic from 12 to 48 partitions. How do you keep per-account order?
The safe route is a new topic with 48 partitions. Switch producers to the new topic, and have consumers drain the old topic completely before they start on the new one. Adding partitions in place is only safe if consumers are fully caught up at the moment of the change, or if events carry versions so the consumer can detect and reject out-of-order arrivals.
Does SQS FIFO give the same guarantee?
Yes, in a similar shape. Messages with the same message group ID are delivered in order, and the next message in a group is not delivered while an earlier one is in flight. Throughput is lower than Kafka's, and a message that keeps failing blocks its group until it succeeds or is dead-lettered.
What about ordering between two different accounts, as in a transfer?
There is none, by design. If a business operation spans two keys, model it as one event keyed by the transfer ID, or as a saga whose steps are each ordered within their own account, and make each step idempotent.

Common mistakes

  • Claiming Kafka preserves order across a whole topic.
  • Using one partition to get total order without noting the throughput ceiling.
  • Processing records from one partition in a thread pool without dispatching by key.
  • Forgetting that retry topics and dead-letter queues reorder messages for a key.
  • Ignoring the effect of changing the partition count.

A strong answer includes

  • States that order is per partition and chooses the account ID as the key
  • Covers producer-side ordering: idempotent producer, a single writer or sequence numbers
  • Covers consumer-side concurrency with serial processing per key
  • Addresses what happens to order when a message fails
  • Mentions that changing the partition count moves keys
  • Adds version numbers so the consumer can detect stale or missing events

Revise: Kafka: partitions and consumer groups

4. How would you configure Kafka so that an acknowledged write is never lost, and what does that cost?

Seniorkafkareplicationdurability

What the interviewer is really testing

Whether you understand how acks, the in-sync replica set and min.insync.replicas combine, rather than reciting acks=all, and whether you can state the availability and latency you give up for durability.

Show the model answer, follow-ups and checklist

Model answer

“Never” has to mean “survives the failures I have planned for”, so I would first say which: the loss of any one broker, including the partition leader, at any moment.

Four settings work together:

  • Replication factor 3, with the replicas in different racks or availability zones.
  • acks=all on the producer. The leader acknowledges only when every in-sync replica has the record.
  • min.insync.replicas=2 on the topic. Without it, the in-sync set can shrink to the leader alone, and acks=all then means one copy. With it, a write is refused unless two replicas have it.
  • Unclean leader election disabled, which is the default. Only an in-sync replica can become leader, so a stale replica never takes over and discards acknowledged data.

With those, every acknowledged record is on at least two brokers, and a new leader is always chosen from brokers that have it.

On the producer I would keep idempotence on, leave retries bounded by delivery.timeout.ms and not by a small count, and handle the final failure callback. A write that was never acknowledged is my problem, not Kafka’s. If the event comes from a database change, an outbox makes sure it is produced at all.

The costs:

  • Latency. Each write waits for a follower, which adds a network round trip, and a longer one across zones.
  • Availability. With two of three replicas down, the partition rejects writes. I am choosing to fail a write over accepting one I might lose. Setting min.insync.replicas to 3 would be a mistake, because a single broker restart would then stop all writes.
  • Storage and network. Three copies of everything, plus replication traffic.

One caveat I would state: by default Kafka acknowledges once the data has been written on the in-sync replicas, without waiting for each one to flush to disk. Its durability comes from replication, so a simultaneous power loss on every replica could still lose recent writes. Spreading replicas across zones is what makes that unlikely.

Likely follow-ups

Why is acks=all without min.insync.replicas not enough?
"All" means all replicas currently in the in-sync set, and that set shrinks when followers fall behind. If it shrinks to the leader alone, acks=all is satisfied by one copy, and losing that broker loses the write. min.insync.replicas sets a floor on how many copies an acknowledgement stands for.
One broker is restarting for an upgrade and another fails. What do producers see?
Partitions whose in-sync set drops to one replica reject acks=all writes with a not-enough-replicas error. The producer retries until delivery.timeout.ms and then reports failure, so the application must buffer, shed or fail upstream. Reads of committed data continue. This is why rolling restarts go one broker at a time and wait for replicas to rejoin.
Would you ever choose acks=1?
Yes, for data where a little loss on leader failover is acceptable and latency or throughput matters more: metrics, logs, clickstream. It is a setting per producer, so one cluster can serve both kinds of workload.
Once the producer has its acknowledgement, where else can the data still be lost?
It is safe in the log until retention removes it. A consumer that is down for longer than the retention period misses it, and a consumer that commits offsets before processing can skip it after a crash. End-to-end safety needs the consumer side to be right as well.

Common mistakes

  • Giving acks=all as the whole answer and leaving out min.insync.replicas.
  • Setting min.insync.replicas equal to the replication factor, so that any single broker outage blocks writes.
  • Ignoring failure handling in the producer, so unacknowledged writes are silently dropped.
  • Claiming there is no cost, without naming latency and reduced write availability.
  • Assuming an acknowledgement means the data has been fsynced to disk.

A strong answer includes

  • Defines the failure being tolerated
  • Lists replication factor 3, acks=all, min.insync.replicas=2 and no unclean leader election
  • Explains what the in-sync replica set is and why the minimum matters
  • Covers the producer: idempotence, retries and handling the final failure
  • Names the costs in latency and write availability
  • Notes that durability comes from replication across separate failure domains

Revise: Kafka: partitions and consumer groups

5. Consumer lag on a topic has been growing for an hour. How do you investigate and fix it?

Seniorkafkaconsumer-lagdebugging

What the interviewer is really testing

Whether you can debug a streaming system methodically: separate arrival rate from processing rate, tell a global problem from a single partition, and know which fixes are capped by the partition count or a downstream dependency.

Show the model answer, follow-ups and checklist

Model answer

Lag is the log end offset minus the committed offset, so it grows when records arrive faster than they are committed. I would find out which side changed, and whether the problem is everywhere or in one place.

First, look at the shape.

  • All partitions rising together. Either the produce rate went up or the consumers as a whole slowed down. I compare the produce rate with an hour ago.
  • One or two partitions rising. A hot key is sending a large share of traffic to one partition, or one consumer is stuck, or a poison record is being retried in place.
  • Committed offsets not moving at all. The consumers are making no progress, so I check whether they are alive, crash-looping or stuck in rebalances.

Second, find the bottleneck in the consumer. I look at processing time per record and at what the consumer is waiting on. Low CPU with rising lag usually means a slow downstream call to a database or an API. I also check the rebalance count, because a group that keeps rebalancing spends its time rejoining and reprocessing.

Then fix the cause.

  • More load than capacity. Add consumers, up to the number of partitions. If there is already one consumer per partition, more instances do nothing, and I need more partitions or faster processing.
  • Slow processing. Batch the downstream writes, add concurrency within a partition by key, or fix the slow dependency. Adding consumers against a struggling database makes it worse.
  • A poison record. Move it to a dead-letter topic and commit past it.
  • A hot key. Split the key if the ordering requirement allows, or isolate that tenant.

Meanwhile, watch the clock. If lag measured in time is approaching the topic’s retention, unread data will be deleted. I would extend retention before doing anything else.

Afterwards I would alert on lag as time behind, and on its trend, so that this pages in ten minutes and not after an hour.

Likely follow-ups

You have 12 partitions and 12 consumers, and lag is still rising. What now?
More consumers would sit idle, so the gain has to come from each consumer doing more. Process in larger batches, write downstream in bulk, and add per-key concurrency inside the consumer. Longer term, increase the partition count and plan for the effect on key ordering. If the bottleneck is downstream, scale that first.
Lag is concentrated on one partition. How do you tell a hot key from a stuck consumer?
Compare the produce rate per partition. If that partition receives far more than the others, it is skew, and the key distribution shows which key. If its input rate is normal and its committed offset is not moving, the consumer is stuck, usually retrying one record, and its logs show the same offset failing repeatedly.
The backlog is 50 million records. How do you catch up without hurting downstream systems?
Estimate the drain time: backlog divided by the consume rate minus the produce rate. Scale consumers within what the downstream can take, and rate limit the catch-up if necessary. If stale records have no value, consider skipping to the latest offset and backfilling from a source of truth, which is a product decision and not only an engineering one.
Why alert on time lag and not on message count?
A count means different things at different throughputs: 100,000 records is seconds of work on a busy topic and hours for a slow consumer. Time behind maps directly to how stale the consumer's output is, and to how close it is to losing data at the retention limit.

Common mistakes

  • Jumping straight to adding consumers without checking the partition count or the real bottleneck.
  • Not distinguishing lag on all partitions from lag on one.
  • Forgetting that retention can delete unread data while you investigate.
  • Scaling consumers against a slow shared dependency and making it slower.
  • Ignoring rebalances as a cause of zero progress.

A strong answer includes

  • Defines lag and frames it as arrival rate against processing rate
  • Separates all-partition lag from single-partition lag and gives causes for each
  • Checks consumer health, processing time, downstream latency and rebalance frequency
  • Notes that consumers beyond the partition count are idle
  • Mentions poison records and hot keys
  • Protects data by comparing lag with retention
  • Proposes alerting on time behind and on trend

Revise: Kafka: partitions and consumer groups

6. A consumer group rebalances every few minutes and throughput has collapsed. What is going on, and how do you fix it?

Staffkafkarebalancingconsumer-groups

What the interviewer is really testing

Whether you understand how Kafka decides a consumer is dead, the difference between heartbeat and poll-interval failures, how slow processing creates a self-sustaining rebalance loop, and which protocol and configuration changes reduce the damage.

Show the model answer, follow-ups and checklist

Model answer

A rebalance happens when the group coordinator believes membership has changed. If that happens every few minutes, either members really are coming and going, or healthy members are being judged dead. The consumer logs and the coordinator’s stated reason for each rebalance tell me which.

Healthy members judged dead. This is the most common cause. A consumer must call poll() within max.poll.interval.ms, five minutes by default. If one batch takes longer, because of a slow downstream call or too many records per poll, the consumer leaves the group. Its partitions move to other members, who inherit the same slow batch and may time out in turn. When the original consumer finishes, its commit fails because it no longer owns the partition, and it rejoins, which triggers another rebalance. The group spends its time reassigning partitions and reprocessing the same records.

The fix is to make each poll loop finish in time: lower max.poll.records, speed up or time-box the processing, or raise the interval to match the real worst case.

Missed heartbeats. Long garbage-collection pauses or CPU starvation can exceed session.timeout.ms. I would check pause times and container CPU limits.

Members really changing. Crash loops, an autoscaler that adds and removes instances as lag moves, spot instance churn and rolling deploys all cause repeated rebalances. I would fix the crashes, damp the autoscaler, and use static membership (group.instance.id) so that a consumer which restarts within the session timeout keeps its assignment.

Then reduce the cost of each rebalance. Under the original eager protocol every consumer gives up every partition each time, so the whole group stops. The cooperative sticky assignor moves only the partitions that have to move. On Kafka 4.0 and later, the newer consumer group protocol has the broker compute assignments and makes rebalances incremental.

Finally, repeated rebalances mean repeated redelivery. I would confirm that the consumers are idempotent, and add an alert on rebalance rate.

Likely follow-ups

How do you tell a max.poll.interval.ms problem from a session timeout?
The client logs say which. A poll timeout produces a message that the consumer is leaving the group because the time between polls exceeded max.poll.interval.ms, and a later commit fails with CommitFailedException. A session timeout appears on the coordinator as a member removed for missing heartbeats, and usually lines up with garbage-collection pauses or CPU throttling on the client.
Why not set max.poll.interval.ms to an hour?
It hides the symptom and delays detection of a consumer whose processing thread is truly stuck, because the heartbeat thread keeps it in the group. Its partitions would go unprocessed for up to an hour. Size the interval to the real worst-case batch with some margin, and bound the batch.
What does static membership change during a rolling deploy?
Each consumer has a stable group.instance.id. When it restarts and rejoins within session.timeout.ms it gets its old partitions back and no rebalance is triggered. Its partitions simply wait while it is down, so the session timeout is sized to cover a restart.
What is the correctness risk during a rebalance?
Records that were processed but not yet committed when a partition was revoked are delivered again to the new owner. Commit in the partition-revoked callback where you can, and make processing idempotent, because a consumer that was removed without knowing it cannot commit at all.

Common mistakes

  • Blaming the brokers or the network before reading the consumer's own logs.
  • Not knowing the difference between a heartbeat timeout and the poll interval.
  • Raising timeouts to very large values without bounding processing time.
  • Ignoring autoscaling or deploy churn as a source of membership changes.
  • Overlooking the duplicate processing that each rebalance causes.

A strong answer includes

  • Explains what triggers a rebalance and separates real membership change from false failure detection
  • Identifies slow processing that exceeds max.poll.interval.ms and the loop it creates
  • Mentions session timeouts caused by GC pauses or CPU starvation
  • Proposes bounded batches and correctly sized timeouts
  • Uses static membership for restarts and deploys
  • Uses cooperative or broker-coordinated rebalancing to limit the pause
  • Notes duplicates and the need for idempotent processing

Revise: Kafka: partitions and consumer groups

7. Kafka says it supports exactly-once. Does that mean my consumer never processes a message twice?

Seniordelivery-guaranteesexactly-oncekafka

What the interviewer is really testing

Whether you can state precisely what Kafka's idempotent producer and transactions guarantee, where that guarantee ends, and what you build for a consumer with side effects outside Kafka.

Show the model answer, follow-ups and checklist

Model answer

No. It means something narrower that is still useful, and I would explain exactly where the boundary is.

Kafka’s exactly-once is two features.

The idempotent producer gives each producer an ID and each batch a sequence number per partition. If the producer retries a batch because the acknowledgement was lost, the broker recognises the sequence number and does not append it again. That removes the duplicates created by producer retries.

Transactions let a producer write to several partitions and commit consumer offsets atomically. In a consume-transform-produce loop, the output records and the input offsets either both commit or both abort. Consumers that read with read_committed never see aborted output. Kafka Streams turns all of this on with one setting.

So for a pipeline that reads from Kafka and writes to Kafka, the result is as if each input was processed exactly once. Notice what that does not say. After a crash, the input is read and processed again. The first attempt’s output was aborted, so it is invisible. The processing ran twice, and the committed effect appears once.

That is why the guarantee stops at Kafka’s edge. If my consumer charges a card, writes a row to PostgreSQL or sends an email, that effect is not part of the Kafka transaction. If the consumer crashes after the side effect and before the commit, the side effect happens again on redelivery.

For a consumer with external effects, what I build is at-least-once delivery plus idempotent processing. I record the event ID in the same database transaction as the business change, or use a conditional write, or pass an idempotency key to the external API. The result is usually called effectively-once.

I would also mention what transactions cost: extra latency, because read-committed consumers wait for the commit, and more moving parts. I would use them for stream processing, and idempotent consumers everywhere else.

Likely follow-ups

Could you get true exactly-once into a database by storing offsets there?
Yes, for that one database. Write the result and the partition offset in the same database transaction, and on startup seek to the stored offset instead of the one Kafka holds. Output and progress then cannot diverge. It is the same idea as Kafka's transactions, with the database doing the atomic commit.
Does the idempotent producer stop duplicates if my service publishes the same event twice?
No. It deduplicates retries of the same batch inside the client library, identified by sequence number. Two separate send calls are two records. Duplicates caused by application retries need a business-level ID that consumers deduplicate on.
Why is exactly-once delivery impossible in general?
A sender cannot distinguish a lost message from a lost acknowledgement, so after a timeout it must either resend and risk a duplicate, or not resend and risk loss. No number of extra acknowledgements closes that gap, which is the two generals problem. What systems achieve is an exactly-once effect, by making duplicates detectable.
SQS FIFO also advertises exactly-once processing. Is that different?
It deduplicates sends: a second message with the same deduplication ID within five minutes is accepted but not delivered again. On the consuming side, a worker that fails to delete a message before the visibility timeout expires receives it again. So the consumer still has to be idempotent.

Common mistakes

  • Answering yes and treating the feature as a general guarantee.
  • Answering that exactly-once is impossible and dismissing what Kafka does provide.
  • Not knowing that side effects outside Kafka are excluded.
  • Confusing the idempotent producer with an idempotent consumer.
  • Leaving out the latency cost of transactions and read-committed consumers.

A strong answer includes

  • Says no, then defines what Kafka's guarantee covers
  • Explains the idempotent producer: producer ID and sequence numbers
  • Explains transactions as an atomic commit of output and offsets, read by read_committed consumers
  • States that processing can still run twice and external side effects can repeat
  • Gives the practical answer: at-least-once delivery with idempotent processing
  • Mentions the cost of transactions and where they are worth it

Revise: Delivery semantics

8. Your consumer credits a customer's wallet for each payment event, and the queue delivers at least once. How do you make sure nobody is credited twice?

Senioridempotencydeduplicationconsumers

What the interviewer is really testing

Whether you can design deduplication that is actually atomic with the business write, choose the right identifier, and reason through each crash point instead of saying "make it idempotent".

Show the model answer, follow-ups and checklist

Model answer

I would make the credit, and the record that it has been applied, a single atomic step, keyed on an ID that identifies the payment and not the delivery.

The ID. Each event carries a unique ID set by the producer when the payment happened, such as the payment ID. A broker message ID is not enough: if the producer publishes the same payment twice, those are two different messages.

The transaction. The consumer does the following in one database transaction:

  1. Insert the event ID into a processed_events table that has a unique constraint on it.
  2. If the insert fails with a unique violation, the event has already been applied. Roll back, acknowledge the message and stop.
  3. Otherwise insert the ledger entry and update the balance.
  4. Commit, then acknowledge.

Every failure point is covered. A crash before the commit leaves nothing behind, and the redelivery does the work. A crash after the commit and before the acknowledgement causes a redelivery that hits the unique constraint and is skipped. Two consumers handling the same event at once race on the insert, and the database lets only one win.

Checking with a SELECT and then writing would not be safe, because both consumers could see “not found”. The unique constraint is what makes it correct.

A simpler variant. If the wallet is a ledger, I can put the unique constraint directly on the ledger entry’s payment_id and drop the separate table. The business data then protects itself, permanently.

Retention. A separate deduplication table grows for ever unless it is pruned. I would keep entries for longer than the longest possible redelivery, including a redrive from a dead-letter queue, so weeks and not hours. The ledger constraint has no such window, which is why I prefer it for money.

What I would not do is deduplicate only in a cache such as Redis. It is not atomic with the balance update, and it can lose keys in a failover.

Likely follow-ups

The consumer also has to call an external API to send a receipt. How do you stop that repeating?
It cannot join the database transaction, so make it idempotent at the far end by passing the event ID as an idempotency key, if the provider supports one. Otherwise write a "receipt pending" row in the same transaction and have a separate sender work through those rows and mark each one sent. That narrows duplicates to a small crash window, and a rare repeated receipt is harmless.
Events for the same wallet can arrive out of order. Does deduplication handle that?
No, that is a separate problem. Deduplication stops the same event applying twice. Credits and debits recorded as ledger entries commute, so their order does not change the balance. For state changes that do not commute, carry a version per wallet and reject or park an event that arrives ahead of its predecessor.
How large does a deduplication table get, and how do you prune it?
One row per event, so at 1,000 events a second it gains about 86 million rows a day. Partition it by day and drop whole partitions older than the window, which is far cheaper than deleting rows. The window must exceed the longest time after which a message could still be redelivered.
Why not rely on SQS FIFO or Kafka transactions and skip all this?
SQS FIFO deduplicates sends within five minutes and still redelivers when a consumer fails before deleting the message. Kafka transactions cover writes to Kafka, not to the wallet database. Both reduce duplicates, and neither removes the need for the consumer's own guard.

Common mistakes

  • Deduplicating on the broker's message ID instead of a business event ID.
  • Checking for the ID and applying the credit in separate steps or separate transactions.
  • Acknowledging the message before the database transaction commits.
  • Keeping deduplication state only in a cache with a short TTL.
  • Forgetting that the same message can be delivered to two consumers at once.

A strong answer includes

  • Uses a producer-assigned business ID as the deduplication key
  • Applies the ID insert and the balance change in one transaction
  • Relies on a unique constraint, not a prior read
  • Acknowledges only after commit and walks through each crash point
  • Addresses how long deduplication records are kept
  • Prefers a permanent constraint on the ledger for money
  • Handles external side effects separately

Revise: Idempotency

9. Your service saves an order to its database and then publishes an event to Kafka. What can go wrong, and how do you fix it?

Senioroutboxdual-writeconsistency

What the interviewer is really testing

Whether you recognise the dual-write problem without being told its name, understand why retries and reordering the two writes do not solve it, and can describe the transactional outbox with its relay options and delivery guarantee.

Show the model answer, follow-ups and checklist

Model answer

This is a dual write: two systems are updated and no transaction covers both. Whichever order the writes go in, there is a failure.

  • Database first, then publish. If the process crashes, is redeployed or loses its connection to Kafka between the two, the order exists and the event is never sent. Downstream services never hear about the order. Nothing reports an error, so it surfaces later as a reconciliation problem.
  • Publish first, then database. If the commit fails, consumers act on an order that does not exist.
  • Retrying the publish inside the request narrows the window and does not close it, because the process can still die before a retry succeeds.

A distributed transaction across the database and Kafka would fix this in principle. Kafka’s transactions do not extend to an external database, and two-phase commit would tie checkout’s availability to both systems, so I would not go that way.

I would use a transactional outbox. In the same local transaction that inserts the order, the service inserts a row into an outbox table holding the event payload, an event ID and the order ID. The two rows commit or roll back together, so there is an event if and only if there is an order.

A relay then moves outbox rows to Kafka. There are two ways to build it:

  • Polling. A worker selects unpublished rows in order, publishes them and marks them as sent. It is simple. It adds some latency and query load, and it needs care so that two relay instances do not interleave one order’s events.
  • Change data capture. A tool such as Debezium tails the database’s write-ahead log and publishes each outbox insert. Latency is low and there is no polling load, at the price of running CDC infrastructure.

Either relay can crash after publishing and before recording that it did, so events are delivered at least once, and consumers deduplicate on the event ID. I would key the Kafka record by order ID so that one order’s events stay in order.

Likely follow-ups

How does a polling relay preserve order and avoid double publishing when several instances run?
Give each outbox row a monotonically increasing sequence and make sure one aggregate's rows are always handled by one worker, for example by leasing ranges of the aggregate ID hash, or by running a single active relay with a standby. It will still publish a row twice if it crashes before marking it as sent, which is why consumers deduplicate.
The outbox table keeps growing. What do you do?
Delete or archive rows once they are published, in batches, or partition the table by time and drop old partitions. With change data capture you can delete the row in the same transaction that inserts it, because the log still records the insert, so the table stays almost empty.
Could you avoid the outbox by making Kafka the source of truth?
Yes, that is the alternative: write the event to Kafka first and have the service update its own database by consuming it. That removes the dual write, but the service's own state then lags its API responses, so reading your own writes needs extra care. It suits event-sourced designs more than a conventional CRUD service.
Why not capture changes to the orders table directly with CDC and skip the outbox table?
It works and needs no application change, but the events are then row-level changes shaped by the table schema. Consumers become coupled to internal columns, and one business action that touches several tables arrives as several unrelated changes. An outbox lets the service publish a deliberate, versioned event.

Common mistakes

  • Saying "wrap both in a transaction" without recognising that no transaction spans the database and the broker.
  • Proposing to retry the publish and treating that as a guarantee.
  • Publishing before the commit and ignoring events for orders that never existed.
  • Forgetting that the relay delivers at least once, so consumers must deduplicate.
  • Ignoring the order of events for the same aggregate.

A strong answer includes

  • Names the dual-write problem and describes the failure for each order of the two writes
  • Explains why retries and distributed transactions are not the answer
  • Describes the outbox row written in the same local transaction
  • Describes a relay built by polling or by CDC, and the trade-off between them
  • States that delivery is at least once and consumers deduplicate
  • Keys events so that order per aggregate is preserved
  • Mentions cleaning up the outbox table

Revise: Idempotency

10. One malformed message keeps crashing your consumer and the partition is stuck. What do you do now, and how do you stop it happening again?

Seniordead-letter-queuepoison-messagesincident-response

What the interviewer is really testing

Whether you can handle the incident safely (preserve the evidence, unblock, consider ordering) and then design a proper failure policy: error classification, bounded retries, a dead-letter destination with alerting, and prevention at the producer.

Show the model answer, follow-ups and checklist

Model answer

I would split this into getting the partition moving, and then making sure one message can never do this again.

Right now. First I confirm it is a single record: the logs show the same partition and offset failing each time, and lag is rising on that partition only. I save the record’s raw bytes and the stack trace somewhere durable. Then I get past it. The preferred way is to deploy a consumer change that catches the failure and routes the record to a dead-letter topic. If that will take too long, I stop the consumer and advance the group’s committed offset by one for that partition. Skipping by hand is a last resort, and acceptable only because the record has been saved.

Before skipping, I ask whether order matters for that key. If the stream is strictly sequential, such as database change events, skipping one record corrupts what follows. Then the right move is to fix the consumer or the data, not to step over the record.

Longer term, the consumer needs a failure policy:

  • Classify errors. Deserialisation and validation failures are permanent and go straight to a dead-letter topic. Timeouts and 5xx responses are transient and are retried.
  • Bound the retries. A few attempts with exponential backoff and jitter. Delays longer than a few seconds move to retry topics, so the partition is not blocked and the consumer stays inside its poll interval.
  • Dead-letter with context. Publish the original payload with headers for the source topic, partition, offset, error and attempt count, then commit.
  • Alert and assign an owner. An alarm on dead-letter depth and message age goes to the team that owns the consumer, with a documented redrive procedure.
  • Make redrive safe. The consumer is idempotent, so replaying after the fix cannot apply anything twice.

I would also look upstream and ask why a malformed message could be published at all. Schema validation at the producer, with a schema registry enforcing compatibility, stops most poison messages at the source.

Likely follow-ups

A hundred messages a second are suddenly failing, not one. Is the dead-letter queue still the right response?
No. A burst across many messages points to a broken dependency or a bad deploy, not bad data. Dead-lettering would drain the whole stream into the DLQ and lose its order. Stop consuming, with a circuit breaker or by pausing, fix or roll back, and resume from the committed offset.
After the fix, how do you reprocess what is in the dead-letter topic?
Run a redrive job that republishes each record to the original topic, or to a dedicated reprocessing consumer, at a throttled rate. Check first whether each message is still valid, because some will be obsolete. The events are now late and out of order relative to their neighbours, so the consumer must be idempotent and should ignore events older than the state it already holds.
How would this incident look different on SQS?
On a standard queue the poison message would not block the others. It would cycle, reappearing after each visibility timeout, until its receive count passed maxReceiveCount and SQS moved it to the dead-letter queue. The risk is the opposite one: nobody notices, so the alarm on the DLQ matters even more.
Where should deserialisation errors be handled in a Kafka consumer?
Before your handler, because the failure happens while the client is decoding the record. Consume raw bytes and decode in your own code, or wrap the deserialiser, so that a bad payload becomes a value you can route to the dead-letter topic. Otherwise the poll call itself keeps failing on the same offset.

Common mistakes

  • Skipping the offset without saving the message.
  • Catching every exception and acknowledging, which silently drops messages during a transient outage.
  • Retrying in place with no limit.
  • Creating a dead-letter topic with no alerting, owner or redrive process.
  • Ignoring whether skipping the record breaks ordering for its key.
  • Not asking how a malformed message could be published in the first place.

A strong answer includes

  • Confirms it is one record and preserves it before acting
  • Unblocks by dead-lettering or by advancing the offset, and says which is preferred
  • Considers ordering before skipping
  • Distinguishes transient from permanent failures
  • Describes bounded retries, retry topics and a dead-letter topic with metadata
  • Adds alerting, ownership and an idempotent redrive
  • Addresses prevention at the producer with schema validation

Revise: Dead-letter queues and retries

11. Your consumer calls a third-party API that fails about 2% of the time. How should it retry?

Mid-levelretriesbackoffdead-letter-queue

What the interviewer is really testing

Whether you can design a complete retry policy: which errors to retry, idempotency before retrying, backoff with jitter, a bound on attempts, where the message waits, and what changes when the failure rate is no longer small.

Show the model answer, follow-ups and checklist

Model answer

I would build the policy around three questions: which failures to retry, how to space the attempts, and what happens when I give up.

Which failures. Retry only what might succeed next time: timeouts, connection errors, and 429, 502, 503 and 504 responses. A 400 or a 422 will fail the same way every time, so it goes straight to the dead-letter queue. For 429 and 503 I respect a Retry-After header when there is one.

Make the call safe to repeat first. A timeout does not tell me whether the API acted. If the call has a side effect, I send an idempotency key derived from the message ID, so that a retry cannot do the work twice. Without that, I should not retry on timeouts at all.

Spacing. Exponential backoff with jitter: a base delay that doubles on each attempt up to a cap, with the actual wait picked at random below that value. Backoff gives the dependency time to recover. Jitter stops every message that failed in the same second from retrying in the same second.

How many, and where. One or two quick retries in-process deal with a blip. After that the message should wait outside the worker. With SQS, I leave it unacknowledged and set its visibility timeout to the backoff delay. With Kafka, I publish it to a retry topic with a delay. After about five attempts over several minutes, it goes to a dead-letter queue with the error attached, and an alarm fires.

When it is no longer 2%. If the failure rate jumps to 50%, per-message retries multiply the load on a service that is already struggling. A circuit breaker should stop the calls for a while, and the consumer should pause so that the backlog waits in the queue.

At 2% independent failures, three attempts leave about 8 messages in a million still failing. Almost everything that reaches the dead-letter queue is then a real problem and worth looking at.

Likely follow-ups

Why is jitter needed if you already have exponential backoff?
Backoff alone keeps failed requests synchronised. Everything that failed at the same instant retries at the same instants, producing spikes at 1, 2 and 4 seconds. Random jitter spreads those retries across the interval, so the recovering service sees a smooth load.
The API times out but had in fact completed the request. What happens on the retry?
Without protection, the action happens twice. With an idempotency key the provider recognises the repeat and returns the original result. If the provider has no such feature, query for the outcome before retrying, or treat the operation as not retryable and send it for manual review.
Retries happen at three layers: the HTTP client, the consumer and the queue. Is that a problem?
Yes. The counts multiply, so three attempts at each of three layers is up to 27 calls for one message, which can turn a partial outage into a full one. Retry at one layer, usually the outermost one that can wait cheaply, and set the others to zero or one.
How do you choose the timeout for each attempt?
From the dependency's latency distribution: a little above its p99 in normal conditions, so that slow but successful calls are not cut off and hung calls do not hold a worker for long. The total of all attempts and waits must also fit inside the message's visibility timeout or the consumer's poll interval.

Common mistakes

  • Retrying every error, including client errors that can never succeed.
  • Retrying a call that is not idempotent after a timeout.
  • Using fixed or immediate retries with no backoff or jitter.
  • Sleeping in the consumer for long delays and blocking the queue or partition.
  • Having no limit on attempts and no dead-letter destination.
  • Ignoring how retries amplify load across layers during a real outage.

A strong answer includes

  • Separates retryable from non-retryable failures
  • Makes the call idempotent before retrying on timeouts
  • Uses exponential backoff with jitter and a cap
  • Limits attempts and moves long waits out of the worker
  • Ends in a dead-letter queue with alerting
  • Adds a circuit breaker or a pause for widespread failure
  • Mentions retry amplification or per-attempt timeouts

Revise: Dead-letter queues and retries

12. An ingestion pipeline's producers can send ten times what the consumers can process. How do you keep it stable?

Staffbackpressureload-sheddingcapacity

What the interviewer is really testing

Whether you separate a burst from sustained overload, know that a buffer only helps with the first, and can design layered responses (scale, push back, shed) with bounded buffers at every stage and the right monitoring.

Show the model answer, follow-ups and checklist

Model answer

First I would find out whether this is a burst or a steady state, because they need different answers.

If producers peak at ten times the consumer rate for a few minutes and the daily average is below capacity, a durable buffer is the right tool. A log such as Kafka holds the burst on disk, and consumers drain it afterwards. I would size it: the excess rate at peak multiplied by the burst length gives the backlog, and the backlog divided by spare capacity gives the drain time. If the product can accept that delay, the remaining job is to make sure retention comfortably exceeds the worst backlog.

If producers sustain ten times capacity, no buffer helps. The backlog grows without limit, and the only choices are to add capacity, slow the producers, or discard data. I would use all three, in layers:

  1. Scale consumers on lag, up to the partition count and up to what the downstream store can absorb. The real bottleneck is often the database behind the consumers.
  2. Push back on producers. Give each producer or tenant a quota at the ingestion API, and return 429 with Retry-After beyond it. Well-behaved clients slow down and buffer locally.
  3. Shed by priority. Decide in advance what may be dropped or sampled: debug telemetry before billing events. Drop at the edge, before spending any work on the data.

Inside the pipeline, every stage needs a bound. A consumer that reads from Kafka into an unbounded in-memory queue in front of a slow writer has only moved the problem into its own heap. Each stage should stop pulling when its downstream is full, so that the backlog builds up in the log, where it is durable and visible.

For monitoring, I would alert on lag measured in time and on its trend, and compare it with retention, because a consumer that falls behind retention loses data silently.

The principle I would state is that the system must degrade by choosing what to delay or refuse, not by filling up and falling over.

Likely follow-ups

The producers are IoT devices you do not control and cannot slow down. What then?
Then the edge has to absorb or discard. Accept everything into a cheap durable log sized for the sustained rate, since storing an event costs far less than processing it, and process a prioritised or sampled subset in real time while batch jobs handle the rest later. If even storing everything costs too much, sample or aggregate at the ingestion tier and say explicitly what fidelity is lost.
Consumers autoscale on lag, but each new consumer triggers a rebalance. How do you handle that?
Scale in larger, less frequent steps with a cool-down, use cooperative rebalancing so that only the partitions that move are paused, and keep enough partitions for added consumers to have something to take. Scale down slowly. An autoscaler that oscillates can lose more throughput to rebalancing than it adds.
How do you size the buffer for a burst?
The backlog is the excess arrival rate multiplied by the length of the burst. For example, 9,000 extra events per second for 10 minutes is 5.4 million events. Drain time is that backlog divided by the spare consumer capacity once the burst ends. Check both the storage for the backlog and whether the drain time meets the freshness requirement.
Why not simply block the producers when the pipeline is full?
Blocking suits producers that can wait, such as batch jobs or other pipeline stages. Producers that serve requests cannot wait: their threads fill up and their own callers time out, so the overload spreads upstream. For them an immediate rejection is better, because it keeps their latency bounded and gives the caller a clear signal.

Common mistakes

  • Answering "put a queue in between" as if a buffer solved sustained overload.
  • Adding consumers without checking the partition limit or the downstream bottleneck.
  • Leaving an unbounded in-memory buffer inside a consumer or a stage.
  • Having no policy for what is dropped or delayed first.
  • Monitoring only CPU or message counts, and not time lag and its trend.

A strong answer includes

  • Distinguishes a burst from sustained overload and sizes the buffer for the former
  • States that sustained overload needs more capacity, slower producers or dropped data
  • Applies quotas or rate limits at the edge with explicit rejections
  • Defines priorities for shedding
  • Bounds every internal buffer so the backlog sits in the durable log
  • Scales consumers on lag within partition and downstream limits
  • Monitors lag as time, its trend, and its distance from retention

Revise: Backpressure

13. For a social feed, would you build each user's timeline when a post is written or when the feed is read?

Mid-levelfan-outnews-feedcaching

What the interviewer is really testing

Whether you can describe both models, compare their costs with numbers instead of adjectives, pick one for the stated workload, and name what the choice gives up.

Show the model answer, follow-ups and checklist

Model answer

I would decide from two numbers: how reads compare with writes, and how many followers a typical author has.

Fan-out on read stores each post once. When a user opens the feed, I fetch recent posts from everyone they follow, merge them and return a page. Posting is one cheap write. Reading costs a lookup per followed account, on the request path, every time.

Fan-out on write keeps a precomputed list of post IDs per user in a cache. When someone posts, a background job appends the post ID to each follower’s list. Reading is one lookup. Posting costs one write per follower.

In a consumer social product, feeds are read far more often than posts are written. Suppose there are 20 feed reads for every post, and people follow about 200 accounts. Pull would do 200 lookups on each of those 20 reads, which is about 4,000 lookups for every post written. Push does 200 writes per post, once, off the request path. So I would choose fan-out on write for the general case. It does less total work, and it puts the work where latency does not matter.

The design is then as follows. The post service stores the post and publishes an event. Fan-out workers consume it, look up the followers and append the post ID to each follower’s timeline in Redis, capped at a few hundred entries. The feed service reads the list and hydrates the IDs from a post cache.

I would state what this costs. Timelines are eventually consistent, usually by seconds. Memory is spent on users who never open the app, so I would maintain timelines only for recently active users and build the rest on demand. Deletes and unfollows are filtered at read time.

And it fails for accounts with millions of followers, where one post becomes millions of writes. For those I would pull at read time and merge, which makes the real design a hybrid.

Likely follow-ups

A user opens the app straight after posting and does not see their own post. Why, and how do you fix it?
Their own timeline is updated by the same asynchronous fan-out, which may not have run yet. Insert the post into the author's own timeline synchronously in the post request, or have the client show it locally. The author then reads their own write, while followers remain eventually consistent.
What happens for a user who has not logged in for six months?
Their cached timeline has been evicted or was never maintained, because fanning out to inactive users is wasted work. When they return, the feed service builds a timeline by pull, querying recent posts from the accounts they follow, caches it, and marks them active so that push resumes.
How does this change if the feed is ranked and not chronological?
Fan-out then produces candidates and not the final order. The timeline holds recent candidate IDs, and a ranking step at read time scores and orders them, often adding candidates from other sources. The push or pull question still decides how the candidates are gathered cheaply.
A user unfollows someone. What do you do about that author's posts already in their timeline?
Do not rewrite the timeline synchronously. Filter at read time against the current follow list or a set of recent unfollows, and let the entries age out of the capped list. A background clean-up is optional.

Common mistakes

  • Describing only one model and not comparing costs.
  • Choosing without any numbers for read rate, write rate or follower counts.
  • Doing the fan-out synchronously inside the post request.
  • Storing full post content in every timeline instead of IDs.
  • Never mentioning accounts with very large follower counts.
  • Ignoring inactive users and the memory spent on them.

A strong answer includes

  • Explains both models and where each puts the cost
  • Uses the read-to-write ratio and a typical follower count to choose
  • Makes fan-out asynchronous through a queue or log
  • Stores capped lists of post IDs and hydrates at read time
  • States the trade-offs: eventual consistency, memory, deletes and unfollows
  • Flags the large-follower case and points to a hybrid

Revise: Fan-out on write vs fan-out on read

14. Your feed uses fan-out on write. An account with 80 million followers posts. What happens, and how do you redesign for it?

Stafffan-outhot-keysnews-feed

What the interviewer is really testing

Whether you can quantify a hot-key problem, see its second-order effects on other users, and design a hybrid with a reasoned threshold, isolation between workloads and a read path that stays fast.

Show the model answer, follow-ups and checklist

Model answer

With pure fan-out on write, that one post becomes 80 million timeline writes. If the fan-out tier does 200,000 writes a second, that is 400 seconds, nearly seven minutes, of its entire capacity.

The effects go beyond one slow post. The job sits in the same queue as everyone else’s, so ordinary users’ posts are delayed behind it. Followers receive the post minutes apart, and a reply can arrive before the post it answers. Most of the writes are wasted, because most followers will not open the app before the entry scrolls out of their capped timeline. If two or three such accounts post during a live event, the backlog compounds.

The redesign is a hybrid, which treats this as the hot-key problem it is:

  • Do not fan out for very large accounts. Above a follower threshold, the post is stored once and indexed by author.
  • Merge at read time. For each reader, the feed service takes the precomputed timeline, fetches recent posts from the large accounts that reader follows, and merges the two. I keep each user’s list of followed large accounts small and cached, so this is a handful of lookups.
  • Cache the hot posts. A celebrity’s recent posts are read by millions, so one cached list per celebrity serves all of them.

The threshold is a tuning value. I would start at around 100,000 followers and adjust it from the observed fan-out lag. It should not be a cliff either: an account hovering near it should not flip between modes, so I would add some hysteresis.

Around that I would add protections that help in any case: separate queues or priorities, so that a large fan-out cannot starve small ones; fan-out only to recently active followers; and batched writes to the timeline cache, grouped by shard.

The cost is a more complex read path with two sources to merge. Read latency now depends on a second lookup, so that lookup needs a tight timeout and a fallback to the precomputed timeline alone.

Likely follow-ups

How do you pick the threshold, and what if an account goes viral and crosses it overnight?
Derive it from capacity: the largest fan-out you can finish within your freshness target, given the tier's write rate and its normal load. Evaluate it for each post from the current follower count and queue depth, not from a static flag, so that a newly large account is handled correctly at its next post. Its older posts already in timelines stay there, and the read path deduplicates by post ID when merging.
Followers want push notifications for this account's posts. Does the same problem come back?
Yes, because notifications are inherently fan-out on write. Treat it as a separate, rate-limited pipeline: send first to followers who opted in for that account, spread the rest over minutes, skip inactive devices, and accept that delivery is staggered. Its queue must be isolated from the timeline fan-out.
The read path now merges two sources. How do you keep it fast?
Fetch both in parallel. The celebrity side is one cached list per followed large account, usually a few keys fetched in one round trip. Merge by timestamp, or pass both to the ranker, and bound the celebrity fetch with a short timeout so that a cache miss gives a slightly incomplete feed and not a slow one.
Is there a version of this problem on the read side?
Yes. A user who follows tens of thousands of accounts is expensive for fan-out on read, and in a hybrid they may follow many large accounts. Cap the number of followed accounts that are merged at read time, prioritise them by affinity, and rely on the pushed timeline for the rest.

Common mistakes

  • Describing only the slow post and missing the effect on every other user's fan-out.
  • Proposing more fan-out workers as the whole fix.
  • Switching the entire system to fan-out on read.
  • Giving a threshold with no reasoning about what sets it.
  • Forgetting that the merged read path needs caching and a timeout.

A strong answer includes

  • Quantifies the fan-out: number of writes, and time at a stated rate
  • Names the side effects: queue starvation, staggered delivery, wasted writes
  • Proposes push below a threshold and pull-and-merge above it
  • Explains why the read-side pull is cheap: few celebrities per reader, highly cacheable
  • Treats the threshold as tunable and tied to capacity
  • Adds isolation or priority between large and small fan-outs
  • States the added read-path complexity and how to contain it

Revise: Fan-out on write vs fan-out on read