Absorbing the Spike: Designing Survey Response Ingestion

Published On: 29 October 2026.By .

Quick answer

A survey platform's hardest path is the submit write: a lost response is gone for good, and traffic arrives as a spike rather than a stream. The design accepts fast and processes later. The API appends the response to a replicated Kafka topic and returns 202 Accepted in milliseconds, consumers write to Cassandra, Redis and downstream systems at their own pace, a transactional outbox closes the gap when the publish fails, and a client submission token makes every redelivered write idempotent. At 10 million monthly active users and 2 billion responses a month, that is roughly 770 writes a second average and 7,700 at peak, absorbed without losing an acknowledged response.

System design · Survey platform · Write path

A survey platform is read-heavy overall, but its most important path is a write: the moment a respondent presses Submit. A lost response cannot be recovered. The respondent will not fill in the form again, and the survey owner will never know the answer existed.

That write path also has the worst traffic shape in the system. A company sends a survey to every employee at 9 AM, or a link gets shared on social media. Thousands of people submit within the same few minutes, and then traffic drops back to almost nothing.

This post designs response ingestion for a SurveyMonkey-scale platform one problem at a time. Each section follows the same pattern: the problem, the naive fix most of us reach for first, why it fails, and the proper design. You don't need prior Kafka or Cassandra experience; the terms are explained as they come up.

The numbers

These planning assumptions are used throughout the post.

AssumptionValue
Monthly active users10M
Responses per month2B
Average response payload2 KB
Peak-to-average ratio10×

From those:

Derived figureValueHow
Average writes/sec~7702B ÷ 30 days ÷ 86,400 s
Peak writes/sec~7,70010× average
Peak ingest bandwidth~15 MB/s7,700 × 2 KB
Raw response storage~48 TB/year2B × 2 KB × 12 months, before replication

And the targets for the submit endpoint:

  • p99 latency under 200 ms, so the "Thank you" screen appears immediately.
  • Zero loss of acknowledged responses. Once the user sees "Thank you", the response must exist.
  • 99.9% availability on the submit path, including while the database is degraded.

The average is easy to serve. The design is driven by the peak: 10× the normal rate, arriving with no warning, for minutes at a time.

Terms used in this post

TermMeaning here
Log / Kafka topicAn append-only list of messages stored on disk and copied to several servers (brokers). New messages go on the end; readers keep track of where they are.
PartitionA topic is split into partitions so it can be written and read in parallel. Each message goes to one partition, chosen by its key.
Producer / consumerThe producer writes messages to the topic (here, the API). Consumers read them and do the work (here, storing responses).
OffsetA consumer's bookmark: the position of the last message it has finished. After a restart, it resumes from there.
Consumer lagHow many messages are in the topic that consumers haven't processed yet. In other words, the backlog.
202 AcceptedAn HTTP status meaning "we have your request and will process it", as opposed to 201 Created, which means "it's done".
IdempotentDoing the same operation twice has the same effect as doing it once.
Partition key (Cassandra)The part of the primary key that decides which group of nodes stores a row. Rows with the same partition key are stored together.

1. Surviving the spike

Problem Submissions arrive at up to 7,700 per second in sudden bursts. Every one of them must be stored, and the respondent should see "Thank you" within 200 ms.

Naive fix Handle each submission in a single request: validate it, insert it into the database, and return success once the insert finishes.

RespondentResponse APIResponse DBPOST responseINSERTOK201 CreatedRespondent waits for the whole chain, including the database

The naive path. The respondent's request stays open until the database write finishes, so any database slowness becomes submit slowness.

Why it fails This works in a demo but not at scale. The API and the database are tied together in three ways:

  • Latency. The respondent waits for the database. A slow disk, a garbage-collection pause or a node being replaced shows up directly on their screen.
  • Capacity. The database must be sized for the peak of 7,700 writes/sec, even though the average is 770 and the peak lasts only minutes a day.
  • Failure. When the database slows down, open requests pile up, connection pools run out and the API starts timing out. Clients retry, which adds load to a database that is already struggling. One slow database turns into an outage of the whole submit path.

The obvious follow-up is to buy a bigger database. That raises the ceiling, but you pay for peak capacity all day, and respondent latency is still tied to database latency. The failure mode is the same, it just starts at a higher number.

Proper design The respondent doesn't need their answer to be indexed, counted and stored in its final table. They only need to know it is safe. So split ingestion into two halves: accept the response quickly and durably, then process it later at a pace the database can handle.

Think of a busy restaurant. The waiter doesn't stand in the kitchen until your food is cooked. They pin your order on the ticket rail and go back to the tables. The rail absorbs the rush, and the kitchen works through it at its own speed. A durable log such as Kafka is that ticket rail.

RespondentGatewayrate limitResponse APIvalidateKafka topicsurvey-responsesappendacks=all202 AcceptedACCEPT · synchronous, millisecondsPROCESS · asynchronous, at the consumers' paceStorage consumersAnalytics consumersWebhook consumersbatch writeincrementHTTPCassandraresponsesRedislive countsExternal systems

The response API only appends to Kafka and replies. Separate consumer groups read the same topic at their own pace and write to their own stores.

The Response API now does three things. It validates the payload, appends it to a Kafka topic, and returns 202 Accepted once Kafka confirms the message is stored on more than one server. Everything else is done by consumers that read the topic.

RespondentResponse APIKafkaConsumerCassandraPOST responseappend, acks=allreplicated202 AcceptedACCEPTrespondent donepoll batchmessageswrite batchOKcommit offsetPROCESSat its own pace

Two halves. The respondent is done after the first four messages. Storage happens afterwards, at the consumer's pace, and the offset is committed only after the database write.

What this changes:

  • Each request does a small, fixed amount of work. Appending to a log is a sequential write. Its cost doesn't depend on how many responses are already stored or how busy the database is.
  • A spike becomes a backlog instead of an outage. During a burst the topic grows and consumer lag rises. Lag is a number you can graph and alert on, and it drains by itself once the burst passes.
  • You choose the database's write rate. Consumers batch writes and cap concurrency, so the database sees a smooth load instead of the raw spike.
  • New features stay off the request path. Live counters, webhooks and fraud checks are separate consumers. Adding one doesn't touch the submit endpoint.

This design only works if a 202 really means the response is safe, and that's the next problem.

2. Making "Accepted" mean durable

A 202 is a promise. If the response can still be lost after it's sent, the design has only moved the failure somewhere harder to see. The promise can break in three places: when the API writes to Kafka, when Kafka is down, and when a consumer reads from Kafka.

2a. Writing to Kafka

Problem The API must only send 202 when the response will survive a server crash.

Naive fix Send the message and reply immediately ("fire and forget"), or wait only for the main broker to confirm (acks=1). Both are faster than waiting for copies.

Why it fails Each partition has one leader broker that takes writes and followers that copy from it. With acks=1 the leader confirms as soon as it has the message itself. If it crashes before a follower has copied it, a follower takes over without that message. The respondent saw "Thank you", but the response is gone.

acks=1Leader writesLeader acks, API sends 202Leader crashes before copyNew leader: response missingacks=all, min.insync.replicas=2Leader writesFollower copies2 copies exist, API sends 202Leader crashes: copy survives

With acks=1 the API can reply before any copy exists, so one crash loses the response. With acks=all and min.insync.replicas=2, at least two brokers hold it before the 202 is sent.

Proper design Keep three copies, and don't confirm until at least two of them have the message.

properties
# topic
replication.factor=3
min.insync.replicas=2

# producer
acks=all
enable.idempotence=true

Why each setting, and why not something simpler:

  • replication.factor=3: each partition is stored on three brokers, so losing one broker doesn't lose data.
  • acks=all: the leader confirms only after all in-sync followers have the message. On its own this isn't enough. If two followers fall behind and drop out of the in-sync set, "all" means just the leader, and you're back to acks=1.
  • min.insync.replicas=2: closes that gap. Kafka refuses the write unless at least two copies are in sync. Why 2 and not 3? With 3, a single broker restart would block every write. With 2, you survive one broker being down and still never acknowledge a single copy.
  • enable.idempotence=true: the producer retries failed sends. This setting stops those retries from creating duplicate messages in the log.

2b. When Kafka is unavailable

Problem If the Kafka cluster can't accept writes, the API has nowhere safe to put the response.

Naive fix 1: return an error Reply 503 and let the client retry. It's simple, but it hands the problem to the respondent's browser, and many respondents give up.

Naive fix 2: write to both Insert into the database and publish to Kafka as two separate steps. This is the dual write, and it's worse than it looks. When one step succeeds and the other fails, the two systems silently disagree, and nothing reports it.

Response APIDatabaseKafka1. INSERT: succeeds2. publish: times outout of sync

The dual write. Two independent writes with nothing tying them together: when the second fails, the database and Kafka disagree and nobody is told.

Naive fix 3: always use an outbox Write the response and an "outbox" row in one database transaction, and let a background relay publish outbox rows to Kafka. This is safe because both rows commit or neither does. But it puts a synchronous database write back on every request, which is exactly the coupling section 1 removed.

Proper design: use the outbox only as a fallback Kafka is the normal path. Only when the publish fails does the API write the response to a local outbox table and then return 202. A relay retries outbox rows into Kafka once the brokers recover.

Submission arrivesPublish to Kafkaacks=allacked202 Acceptedfailed or timed outInsert into outboxcommittedinsert failed503, client retriesRelayretries outbox into Kafkalater, when Kafka recovers

Outbox as a fallback. The normal path never touches the database. The outbox only takes load while Kafka is failing, and a relay drains it once Kafka recovers.

Normal requests stay fast, and the outbox database only works during a broker incident. Size it for that: at peak, 7,700 responses/sec × 2 KB is about 55 GB for each hour Kafka is down.

2c. Reading from Kafka

Problem A consumer reads a batch, tries to write it to the database, and something goes wrong: a timeout, a crash, a bad record.

Naive fix Let the client library commit offsets automatically on a timer, or wrap the handler in a try/catch that logs the error and carries on.

Why it fails Both move the bookmark forward whether or not the write succeeded. If the offset is committed and then the write fails or the consumer crashes, Kafka believes the message is done. It is never delivered again, and the response is lost without an error anywhere.

Commit, then writeRead messageCommit offsetWrite fails or consumer crashesMessage skipped foreverWrite, then commitRead messageWrite to databaseCrash before commitMessage redelivered

Order matters. Committing before the write can skip a message forever. Writing first and committing after means a crash causes a redelivery, never a loss.

Proper design Commit the offset only after the write succeeds, and decide explicitly what each kind of failure does:

FailureWhat the consumer does
Temporary DB error (timeout, overloaded node)Retry with backoff. Don't commit.
Bad record (fails parsing or a schema check)Send it to a dead-letter topic with the error, then commit. Retrying won't fix it.
Consumer crashes mid-batchNothing to do: uncommitted messages are redelivered to another consumer.
Database down for a long timePause consuming. Lag grows, the API is unaffected, and consumers catch up later.

This guarantees at-least-once delivery: every message is processed one or more times. Alert on dead-letter topic depth, because a dead-letter topic nobody watches is just a slower way to lose data.

3. Duplicates: making writes idempotent

Problem "At least once" means "sometimes twice". Every safety mechanism from section 2 can produce the same response more than once:

  • The client times out waiting for the 202 and submits again.
  • The producer retries a send whose confirmation was lost.
  • A consumer writes a batch, crashes before committing, and the batch is redelivered.
  • Someone replays the dead-letter topic.

Naive fix Generate a fresh ID when the consumer stores the response (a new UUID or now()), or check "does this response already exist?" before inserting.

Why it fails A fresh ID at write time gives every redelivery a different key, so duplicates are stored as separate responses and inflate the survey results. Check-then-insert has a race: two consumers handling the same redelivered message can both see "not found" and both insert, and the extra read adds load to every write.

ID generated in the consumerDelivery 1: new ID a1Row a1 storedRedelivery: new ID b2Row b2 stored: duplicateID = client submission tokenDelivery 1: token t7Row t7 storedRedelivery: token t7Row t7 overwritten: 1 row

Where the ID comes from decides whether a redelivery is a duplicate. A consumer-generated ID creates a second row. A client-generated token overwrites the same row.

Proper design Give each submission an identity that travels with it end to end. Generate a submission token when the survey page loads, send it with the response, use it as the Kafka message key, and use it as the primary key in storage. In Cassandra an INSERT with an existing primary key overwrites the row, so a redelivered message rewrites the same row instead of adding a new one. No read before the write is needed.

Two details are easy to miss:

  • Take timestamps from the API, not the consumer. If storage is organised by submission date, use the time the API accepted the response. Otherwise a backlog drained after midnight is filed under the wrong day.
  • API-side dedupe is optional. The API can remember recent tokens for a few minutes (for example Redis SET NX with a TTL) and answer a retrying client with the same 202 without publishing again. That saves work, but the primary key in storage is the actual guarantee.

4. The viral survey: partitioning

Problem Most of the time traffic is spread across thousands of surveys. Sometimes one survey goes viral and receives most of the traffic. The system must scale even when nearly every submission has the same survey_id.

Two choices decide this: the Kafka message key and the Cassandra partition key.

4a. The Kafka message key

Naive fix Key messages by survey_id. It feels natural, and it keeps each survey's responses in order.

Why it fails Kafka sends every message with the same key to the same partition, and each partition is read by only one consumer in a group. A viral survey lands on a single partition: one consumer does all the work while the others sit idle. Adding consumers doesn't help.

Key = survey_idViral surveyPartition 0ConsumerbusyPartition 1ConsumeridlePartition 2ConsumeridleKey = submission tokenViral surveyPartition 0Consumer1/3 loadPartition 1Consumer1/3 loadPartition 2Consumer1/3 load

Keying by survey_id puts a viral survey on one partition and one consumer. Keying by submission token spreads it across all partitions.

Proper design Ask whether order is actually needed. Responses to a survey are independent of each other, so it isn't. Key by submission token and a hot survey spreads evenly across every partition and consumer. Keep survey_id as the key on topics where order does matter, such as survey edit events.

4b. The Cassandra partition key

Cassandra suits this workload. Responses are append-only, never updated in place and read in bulk per survey. Writes are cheap, and capacity grows by adding nodes. Survey definitions, which need transactions and joins, stay in PostgreSQL.

Naive fix Group responses by survey and day, so "all responses for survey X on day Y" is a single partition read:

sql
PRIMARY KEY ((survey_id, submission_date), response_id)

Why it fails The partition key (survey_id, submission_date) decides which nodes hold the data. For a viral survey, a whole day's responses go into one partition on one set of replicas. A million responses at 2 KB each makes a 2 GB partition, far beyond the roughly 100 MB Cassandra handles comfortably. Those nodes run hot, and compaction and repair on them slow down.

Proper design Add a bucket to the partition key:

sql
PRIMARY KEY ((survey_id, submission_date, bucket), response_id)
-- bucket = hash(submission_token) % 32
(survey_id, date)1 partition~2 GBone replica setfar above the ~100 MB comfort zone(survey_id, date, bucket)32 partitions × ~60 MBspread across the cluster

Without a bucket, a viral survey's day is one 2 GB partition on one replica set. With 32 buckets it becomes 32 partitions of about 60 MB, spread across the cluster.

The same day is now 32 partitions of about 60 MB, spread across the cluster. The cost: reading a survey's day means 32 partition reads instead of one. They run in parallel, and bulk reads are far rarer than writes, so it's a good trade.

5. Live results without slowing ingestion

Problem Survey owners want a results dashboard that updates as responses come in.

Naive fix Run COUNT(*) ... GROUP BY option against the response store whenever the dashboard loads.

Why it fails At 2 billion responses a month, that's a scan over millions of rows per popular survey, on every page load, against the same database ingestion is writing to. Dashboard traffic would slow down storage.

Proper design Add an analytics consumer group that reads the same Kafka topic and increments a Redis counter per survey, question and option. The dashboard reads counters directly. This pattern has two names worth knowing:

  • CQRS (Command Query Responsibility Segregation): writes go to one model (Cassandra), and reads come from another model built for them (Redis counters).
  • Bulkhead: analytics runs in its own consumer group and its own pods. If it falls behind or crashes, ingestion and storage are unaffected.

Kafka's retention also gives you replay. If a counter bug corrupts the results, fix it, reset the analytics consumer to an earlier offset and rebuild. At the average rate of 770 responses/sec, seven days of retention is about 0.9 TB, or about 2.8 TB with three replicas.

Validating the design with a load test

A load test is how you confirm the design behaves as intended. Send the same burst at the submit endpoint in several scenarios and compare them. Drive it at or above the planned peak (7,700 submissions/sec) and watch four things: API latency, error rate, consumer lag and the number of rows that end up stored.

ScenarioExpected behaviour
Synchronous baseline: API writes straight to the databaseThroughput is capped by the database's write capacity. API latency tracks database latency and climbs as concurrency grows. If the database slows down, timeouts and 5xx errors follow.
Async, consumers runningAPI latency is lower and steadier, because the request only includes a log append. Consumer lag rises during the burst and drains afterwards.
Async, consumers stoppedThe API keeps returning 202 and the error rate is unchanged. Lag grows steadily. Nothing reaches the database yet.
Async, consumers restartedConsumers resume from their last committed offset and drain the backlog. Every response that got a 202 is stored exactly once.
Async, database slowed or stoppedSame as stopping the consumers: respondents are unaffected, lag grows, and storage catches up when the database recovers.

The third and fifth rows are the ones that matter. If the database can be slow or down without respondents noticing, the design is doing its job.

Differences you may see

Results depend on the environment, the configuration and the test itself. These are the common reasons a run doesn't match the expectations above, and what each one tells you.

  • API throughput changes when consumers are stopped. If components share compute or storage, stopping the consumers frees capacity for the API. Isolated components shouldn't show this. Either way, the point to confirm is that the API keeps accepting while consumers are down.
  • Produce latency is higher with durable settings. acks=all across three replicas costs an extra replication round trip compared with acks=1 on one broker. Test with the settings you'll run in production, and budget that round trip into the 200 ms target.
  • Only one consumer is busy. If the test sends everything to one survey and messages are keyed by survey_id, all traffic lands on one partition. That's the viral-survey problem from section 4, and it's worth reproducing on purpose.
  • The database is under more pressure while the backlog drains than during the spike. Restarted consumers read as fast as they can. Cap consumer concurrency or batch size so catching up doesn't overload the store.
  • Stored rows outnumber 202s. If there are more rows than accepted requests after a restart, redeliveries are creating new rows. That's an idempotency gap (section 3).
  • The load generator becomes the limit. If the tool generating traffic runs out of capacity, measured latency and throughput describe the tool, not the system. Check that it has headroom before trusting the numbers.

To size the API tier, measure what one instance sustains within the latency target. Divide the planned peak by that figure to get the minimum instance count, then add enough instances that losing one availability zone still leaves at least that many.

The trade-offs you accept

  • Eventual consistency. A response isn't in the results the instant it's submitted. Normally the delay is a few seconds; during a database incident it can be much longer. That's fine for survey results. It wouldn't be for an account balance.
  • Validation must happen before the 202. Once you've accepted a response, you can't tell the respondent it was rejected. Checks that can fail (schema, required questions, survey still open, valid token) must run in the API, against survey definitions it keeps cached so the database stays off the request path.
  • More moving parts. A Kafka cluster to operate, consumer lag to monitor, a dead-letter topic to triage and an outbox relay to maintain.
  • Durability depends on configuration. Replication factor 1 or acks=1 quietly weakens every guarantee above.

What to monitor

SignalWhy it mattersExample alert
Submit p99 latency and error rateThe respondent-facing targetp99 > 200 ms for 2 min
Consumer lag per partitionShows the backlog growing or drainingLag > 10K messages
Partition skewReveals a hot keyOne partition > 3× the median
Produce failures and outbox depthKafka health from the API's sideOutbox depth rising
Dead-letter topic depthRecords that need manual attentionAny growth

Questions that come up

Why Kafka rather than SQS or RabbitMQ?

The design needs retention and replay, several independent consumer groups reading the same stream, and partitioned throughput. A traditional queue works for a single consumer, but a message is gone once consumed, so a new consumer can't backfill and a broken read model can't be rebuilt.

Isn't returning 202 before the database write misleading the user?

Only if the acknowledgement isn't durable. With acks=all across three replicas, an accepted response is as safe as a committed database row. It just isn't in its final table yet.

Does the queue replace rate limiting?

No. A queue absorbs a burst by storing it; it doesn't absorb unlimited load. Keep token-bucket rate limiting at the gateway to stop abuse. For large spikes you know are coming, such as a company-wide survey launch, admission control (a virtual waiting room, as IRCTC uses for Tatkal bookings) protects the system before requests reach it.

Why not exactly-once processing?

Kafka transactions give exactly-once between Kafka topics, but the final write here goes to Cassandra, outside Kafka. At-least-once delivery plus an idempotent write gives the same end result, with less machinery.

Summary

  • Spike: respondents should wait for durability, not for processing. Return 202 once the response is in a replicated log, and let consumers store it at their own pace.
  • Durability: replication.factor=3, acks=all, min.insync.replicas=2; an outbox as a fallback when Kafka is down; offsets committed only after the write succeeds.
  • Duplicates: at-least-once means sometimes twice. Carry a client-generated submission token end to end and use it as the primary key.
  • Viral surveys: key Kafka by submission token, and add a bucket to the Cassandra partition key.
  • Reads: serve live results from counters built by a separate consumer group, never from COUNT(*) on the write path.
  • Operations: accept eventual consistency deliberately, validate everything before the 202, and watch lag, skew and the dead-letter topic.

Designing a write path that cannot drop data?

Auriga IT builds high-throughput ingestion and data platforms for banking, commerce and enterprise clients, including Kafka and NiFi pipelines, Cassandra and Hadoop stores, and the reconciliation that proves nothing was lost. If you are sizing a spike or reviewing a design like this one, we are happy to look at it with you.

Talk to our engineering team

Related content

Stay Close to What We’re Building

Get insights on product engineering, AI, and real-world technology decisions shaping modern businesses.

Raghvendra Awasthi
Raghvendra Awasthi
SDE III
Raghvendra Awasthi is part of the engineering and technology team at Auriga IT.
Go to Top