Counter Consistency with Caches & Replicas
In this article
This guide explains how to keep counter data (like view counts, likes, or inventory levels) consistent when using caches or database replicas. It covers practical strategies to prevent stale reads and lost updates, ensuring your counters are accurate across distributed systems. You'll learn about atomic operations, versioning, and reconciliation techniques that work in real-world scenarios.
What You'll Need
- A basic understanding of caching (e.g., Redis, Memcached) and database replication.
- Access to your application's codebase and the ability to deploy changes.
- Familiarity with your database's transaction and locking features.
Step-by-Step
- Identify all counter write paths. List every place in your code that increments, decrements, or sets a counter. This includes user actions, background jobs, and admin tools. Write them down—you'll need to standardize them.
- Choose a single source of truth. Decide whether the database or the cache is the authoritative store. For most systems, the database is the source of truth, and the cache is a performance layer. If you choose the cache, you must handle persistence and recovery carefully.
- Use atomic operations in the cache. When using Redis, use
INCRorDECRcommands instead of read-modify-write sequences. In Memcached, useincrementanddecrement. These operations are atomic and prevent lost updates when multiple clients write concurrently. - Write-behind with a queue. Instead of writing to the database on every increment, push the increment event to a message queue (e.g., Kafka, RabbitMQ). A consumer processes the queue and applies updates to the database in batches. This reduces database load and allows for retries.
- Handle cache eviction gracefully. When a counter is evicted from the cache (due to TTL or memory pressure), you need to reload it from the database. To avoid a stampede, use a mutex or a “lock” around the reload. Only one request should fetch from the database; others wait or use a stale value.
- Implement a reconciliation job. Periodically (e.g., every hour), compare the cache counter with the database counter. If they differ, update the cache to match the database. This corrects any drift caused by missed events or partial failures.
- For replicas, use session consistency. If you have multiple database replicas, ensure that a user's writes are immediately visible to them. This can be done by pinning a user to a specific replica for a short period after a write, or by using a read-your-writes consistency mechanism.
- Use conditional updates for database writes. When updating the database counter, use an atomic SQL operation like
UPDATE counters SET value = value + 1 WHERE id = ?. Avoid reading the value, modifying it in application code, and writing it back—that's a classic lost-update bug. - Monitor and alert on drift. Set up monitoring to detect when cache and database counters diverge significantly. Use logs and metrics to track the delta. Alert when the delta exceeds a threshold, so you can investigate before it becomes a user-facing issue.
- Test failure scenarios. Simulate cache evictions, replica lag, and network partitions in a staging environment. Verify that your system recovers correctly and that counters remain accurate after these events.
Common Mistakes
- Read-modify-write in application code. Reading a counter, adding 1, and writing it back is not atomic. Two concurrent requests can both read the same value and write the same incremented value, losing one increment.
- Ignoring TTLs. If a cache counter has a TTL, it will disappear. If you don't reload from the database correctly, you might reset the counter to a stale value.
- Using replicas for reads without considering lag. A replica might be seconds behind the primary. If you read a counter from a replica immediately after a write, you might get an old value.
- Not handling cache stampede. When a counter expires, many requests might try to reload it simultaneously, overwhelming the database.
- Forgetting to persist cache counters. If the cache is in-memory and restarts, you lose all counters unless you have a persistence mechanism.
Tips
- Use a dedicated cache for counters with a longer TTL (e.g., 24 hours) and refresh them proactively before expiry.
- Batch database writes from the queue to reduce transaction overhead.
- Consider using a CRDT (Conflict-Free Replicated Data Type) for counters if you need multi-master replication. Libraries like Riak or Redis with CRDT support can simplify this.
- Document your consistency model clearly for your team. Everyone should know whether counters are eventually consistent or strongly consistent.
- Use idempotent operations in your queue consumer. If a message is processed twice, it shouldn't double-increment the counter. Include a unique message ID and deduplicate.
Troubleshooting
Counters are lower than expected. Check if writes are being lost. Look for read-modify-write patterns in your code and replace them with atomic operations. Also, check if the cache is evicting entries before the write-behind queue processes them.
Counters are higher than expected. This often indicates duplicate processing. Check if your queue consumer is idempotent. Also, verify that you're not incrementing on both the cache and the database for the same event.
Cache and database disagree after a restart. If the cache is not persistent, it will be empty on restart. Ensure that your reload logic fetches the current value from the database and doesn't use a stale backup.
Replica reads are stale. If you must read from replicas, implement a “read-your-writes” strategy: after a write, route the user's subsequent reads to the primary for a few seconds, or use a version number.
Cache stampede is causing database load. Use a lock (e.g., Redis SETNX) around the reload. Only one request should fetch from the database; others can wait for the lock or use a stale value.
Frequently Asked Questions
Should I use the cache or the database as the source of truth?
Use the database as the source of truth. The cache is a performance layer. If the cache loses data, you can rebuild it from the database. If the database loses data, you have bigger problems.
How do I handle counter resets?
Resets should go through the same write path. Set the counter to zero in the cache atomically (e.g., SET in Redis) and enqueue a reset event to update the database. This ensures both stores are consistent.
What if I need to decrement a counter?
Use atomic decrement operations. In Redis, DECR; in SQL, UPDATE ... SET value = value - 1. Avoid reading and writing.
Can I use a TTL on cache counters?
Yes, but you must handle reloads correctly. Use a longer TTL (e.g., hours) and implement a reload with a lock to avoid stampede. Alternatively, use a background job to refresh before expiry.
How do I handle counters in a multi-region setup?
Use a global cache like Redis with active-passive replication, or use a CRDT-based counter. For databases, consider multi-primary with conflict resolution. For most cases, a single primary with replicas is simpler and sufficient.
What is the best way to batch database writes?
Use a message queue to accumulate increments, then flush to the database in batches (e.g., every 10 seconds or every 100 increments). Use a single SQL update per counter to apply the delta.