PostgreSQL and Redis synchronization latency under high-concurrency load
0 reputation · 30 Apr 2022, 09:30 UTC
0 reputation · 30 Apr 2022, 09:30 UTC
A documented behavior involves an eventual consistency model where the primary database and distributed cache nodes experience temporary data discrepancies. While custom scaling strategies are employed to prevent cache stampedes, the simultaneous expiration of high-traffic keys appears to trigger tail latency that is difficult to isolate from database contention.
34775 reputation · 30 Apr 2022, 15:38 UTC
Under write‑heavy bursts, strict ACID forces PostgreSQL to hold row‑level locks until transaction commit, which increases lock wait time and can exhaust the connection pool. Relaxing consistency (e.g., staying at READ COMMITTED with asynchronous replicas) shortens lock duration but allows temporary divergence between the primary DB and Redis cache, observed as synchronization latency spikes.
The trade‑off manifests as follows: when the system prioritizes strict ACID, transactions linger longer on hot rows, queuing new connections and raising tail latency. When availability is favored, commits return sooner, reducing lock contention but leaving Redis with stale data until the cache is updated, producing the observed sync lag.
max_connections, use PgBouncer in transaction mode, set statement_timeout, apply SELECT … FOR UPDATE SKIP LOCKED or advisory locks, batch updates into fewer transactions.EXPIRE offsets.SHOW transaction_isolation;max_connections based on CPU/memory.statement_timeout (e.g., 2s) to abort long‑running writes that would otherwise hold locks.UPDATE with UPDATE … WHERE id = $1 RETURNING * combined with FOR UPDATE SKIP LOCKED or use advisory locks to serialize only the necessary fraction.EXPIRE key $((base + RANDOM % jitter)) where jitter is 10‑20% of base TTL.SET/DEL after the DB commit, decoupling cache reload from DB lock duration.pg_stat_activity for lock wait events and redis-cli --latency or LATENCY command during a write‑heavy benchmark (e.g., pgbench -c 200 -T 300).To confirm whether lock contention or cache stampede is the primary driver, could you share the 95th‑percentile lock wait time from pg_stat_activity observed during the latency spike?
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.