Prevent Data Loss When Stream Ingestion Fails
In this article
Stream ingestion services (like Kafka, Kinesis, or custom pipelines) can fail due to network issues, service outages, or configuration errors. This guide shows you how to configure your pipeline so that no data is lost when the ingestion service goes down, using buffering, retries, and dead-letter queues. You'll need access to your ingestion service's configuration and the ability to modify your producer/consumer code.
What You'll Need
- Access to the stream ingestion service (e.g., Kafka, Kinesis, AWS MSK, etc.)
- Access to the producer application that sends data to the stream
- Access to the consumer application that reads from the stream
- Basic understanding of your data schema and volume
- Permissions to change configuration and deploy code
Step-by-Step
- Enable producer acknowledgments. Configure your producer to wait for acknowledgment from the ingestion service before considering a message sent. In Kafka, set
acks=all; in Kinesis, usePutRecordwithSequenceNumberForOrderingand check the response. This ensures the service has durably stored the record. - Set up a local buffer on the producer. If the ingestion service is unreachable, the producer should not drop messages. Use an in-memory queue or a local disk-based buffer (like a file or embedded database) to hold messages until the service is available again. Configure the buffer size to handle your peak data volume and expected downtime.
- Implement retry logic with exponential backoff. When the ingestion service fails, retry sending messages after a delay that increases with each attempt (e.g., 1s, 2s, 4s, up to a max). Add jitter to avoid thundering herd. Most SDKs have built-in retry policies; enable them and set a reasonable max retry count (e.g., 5).
- Add a dead-letter queue (DLQ). After retries are exhausted, send the failed messages to a separate queue or topic (e.g., a Kafka topic named
dlqor an SQS queue). This preserves the data for later inspection and replay without blocking the main pipeline. - Enable consumer checkpointing and idempotent processing. Consumers should regularly save their position (offset) in the stream. When the consumer restarts, it resumes from the last checkpoint, avoiding reprocessing or skipping. Make your consumer idempotent so that processing the same message twice does not cause issues (e.g., use a unique key in a database).
- Use replication and durability settings. For Kafka, set
replication.factorto at least 3 andmin.insync.replicasto 2. For Kinesis, the default is 3 replicas, but ensure your stream has enough shards to handle throughput. This protects against broker failures. - Monitor and alert on failures. Set up metrics for producer errors, buffer fill rate, and DLQ size. Use monitoring tools (like Prometheus, CloudWatch) to alert you when the buffer is near capacity or when messages enter the DLQ.
- Test failure scenarios. Simulate a service outage (e.g., stop the Kafka broker) and verify that data is buffered, retried, and eventually delivered or sent to DLQ. Test consumer restart to ensure checkpointing works.
Common Mistakes
- Ignoring producer acks: If you don't wait for acks, messages may be lost silently.
- Infinite retries without backoff: This can overload the service and cause cascading failures.
- Not having a DLQ: Without a DLQ, messages that fail after retries are dropped forever.
- Checkpointing too frequently or too rarely: Too frequent can slow down the consumer; too rare can cause reprocessing of many messages.
- Forgetting idempotency: If your consumer is not idempotent, reprocessing can cause duplicate records in downstream systems.
- Using a single broker without replication: A single point of failure.
Tips
- Set buffer size based on your expected downtime: e.g., if you expect 10 minutes of downtime and produce 1000 msgs/min, buffer at least 10,000 messages.
- Use a separate DLQ per data type to simplify debugging.
- For cloud services, use managed DLQ features (e.g., Kinesis Data Firehose's error output, SQS DLQ).
- Implement a replay mechanism for DLQ messages: a script that re-sends them to the main stream after the issue is resolved.
- Consider using a message schema registry to avoid data corruption.
Troubleshooting
- Data still lost after enabling acks: Check that your producer is actually waiting for acks and not using async send without callbacks. Verify the service is not rejecting messages due to size limits.
- Buffer fills up and messages are dropped: Increase buffer size, or implement a backpressure mechanism (e.g., slow down the producer). Consider using a disk-based buffer if memory is limited.
- Retries are not working: Check the retry configuration: max retries, backoff multiplier, and whether the SDK is catching the correct exceptions. Ensure the service is actually reachable after the outage.
- DLQ messages are not being consumed: Verify that the DLQ consumer is running and has proper permissions. Check for poison messages that fail deserialization.
- Consumer reprocesses old messages after restart: Check checkpoint configuration: ensure you are committing offsets after processing, not before. If using Kafka, check
enable.auto.commitis false and you are committing manually. - Ingestion service is down for longer than expected: Consider scaling up your buffer or using a fallback ingestion path (e.g., write to a file and later batch-load).
Frequently Asked Questions
What is a dead-letter queue and why do I need one?
A DLQ is a separate queue where messages that repeatedly fail to be processed are sent. It prevents data loss by preserving the failed messages for later analysis and replay, without blocking the main pipeline.
How long should I keep messages in the buffer?
Keep them until the ingestion service is available and the message is successfully acknowledged. The buffer should be large enough to hold data for your maximum expected outage time.
Is it safe to use auto-commit in Kafka consumers?
Auto-commit can cause data loss if the consumer crashes before processing. It's safer to disable auto-commit and commit offsets manually after processing each batch.
Can I use a database as a buffer?
Yes, a database table can act as a durable buffer. Write messages to the table, and have a separate process read and send them to the stream. This is more robust but adds latency.
What if my producer is a mobile app that goes offline?
For mobile apps, use a local database (like SQLite) to store events, then sync when the network is available. This is a common pattern for offline-first apps.
How do I replay messages from the DLQ?
Write a script that reads from the DLQ and sends each message back to the main stream (or to a new topic). Ensure the consumer is idempotent to avoid duplicates.