惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Security Latest
Security Latest
Recorded Future
Recorded Future
人人都是产品经理
人人都是产品经理
S
SegmentFault 最新的问题
Hacker News - Newest:
Hacker News - Newest: "LLM"
C
CXSECURITY Database RSS Feed - CXSecurity.com
博客园 - 三生石上(FineUI控件)
博客园 - 聂微东
P
Privacy & Cybersecurity Law Blog
WordPress大学
WordPress大学
Know Your Adversary
Know Your Adversary
Spread Privacy
Spread Privacy
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
量子位
L
LINUX DO - 热门话题
L
Lohrmann on Cybersecurity
博客园 - Franky
酷 壳 – CoolShell
酷 壳 – CoolShell
T
Tor Project blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
雷峰网
雷峰网
阮一峰的网络日志
阮一峰的网络日志
V
Visual Studio Blog
T
Threatpost
T
Tenable Blog
有赞技术团队
有赞技术团队
大猫的无限游戏
大猫的无限游戏
Engineering at Meta
Engineering at Meta
GbyAI
GbyAI
C
Cisco Blogs
H
Heimdal Security Blog
Attack and Defense Labs
Attack and Defense Labs
A
About on SuperTechFans
Last Week in AI
Last Week in AI
N
News and Events Feed by Topic
T
Threat Research - Cisco Blogs
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
I
Intezer
V
V2EX
Cyberwarzone
Cyberwarzone
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
B
Blog RSS Feed
V
Vulnerabilities – Threatpost
N
Netflix TechBlog - Medium
T
The Blog of Author Tim Ferriss
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
U
Unit 42
PCI Perspectives
PCI Perspectives
P
Privacy International News Feed
D
Docker

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Read Replicas Lie About Consistency. 4 Sync Modes Behind the Lie.
Gabriel Anha · 2026-05-24 · via DEV Community

Your read replica is lying to you, and "eventual consistency" is the lie's polite name. The user clicks Pay, the API returns 200, the next page reads the order from a replica, and the row isn't there yet. Support gets the ticket. You blame "replication lag" like it's weather.

It isn't weather. It's a config choice, and most Postgres clusters are running the default.

The lie, in one paragraph

A read-after-write that returns stale data is a contract violation. The user gave you a write, you accepted it, you confirmed it, and then you served them old data on the next request. There's no philosophical defence of that. "We're eventually consistent" is what you say to the postmortem doc when you didn't pick a stronger guarantee at config time.

Postgres gives you five settings on a single knob called synchronous_commit, and they buy completely different guarantees at completely different costs. Only one of them prevents a read replica from serving stale rows. Most teams run a global default of on and have never typed the other four values into a session.

The 4 (well, 5) sync modes, ranked by guarantee

synchronous_commit has five legal values. Ranked from "fire and forget" to "wait until the replica has the row visible to queries":

  1. off: primary returns commit before fsync to its own WAL. A primary crash inside the next few hundred milliseconds loses the transaction. Don't ship this unless you really mean it.
  2. local: primary returns commit after its own WAL fsync. Replica state is irrelevant. This is the value when no synchronous_standby_names is set.
  3. on (the default) / remote_write: primary waits for the synchronous standby to receive the WAL into its kernel. Not flushed to disk. Not replayed. A replica OS crash before flush can still lose it.
  4. remote_flush: primary waits for the synchronous standby to fsync the WAL to its disk. The replica can survive a crash and still have the record. But it hasn't been replayed yet, so a SELECT on that replica won't see the row.
  5. remote_apply: primary waits for the synchronous standby to apply the WAL, actually replaying it into the database. A SELECT on that replica will see the row immediately after the COMMIT returns.

The first four are about durability. Only the last one is about read-after-write consistency on the replica. That's the whole point of this post: if you want the replica to never serve stale data, remote_apply is the only setting that gives you that.

Everything else is theatre.

What each mode guarantees vs costs

A rough latency table from a 3-node Postgres 16 cluster in one AWS region (us-east-1, gp3, c6i.large), measured with pgbench -c 16 -j 4 -T 60 -N. Treat numbers as order-of-magnitude, not benchmarks:

Mode Survives primary crash? Survives replica crash? Replica reads after-write? p99 commit latency
off no no no ~0.4 ms
local yes no no ~1.2 ms
on / remote_write yes no no ~2.0 ms
remote_flush yes yes no ~3.5 ms
remote_apply yes yes yes ~6.0 ms

The spread between off and remote_apply is roughly 15x. Across a region (say a standby in Frankfurt and a primary in Dublin, ~25 ms RTT) the same table shifts: remote_apply becomes 50-60 ms per commit. That's not a footnote. That's a product decision.

Most teams who default to on and assume "we're durable" are running with the replica can crash and lose the record setting. That's fine for a lot of workloads. It is not fine for payment intent records or permission grants.

Synchronous standbys and the quorum trick

synchronous_commit interacts with one other setting: synchronous_standby_names. Without that one set, none of the remote_* modes do anything. There's nobody to wait for, so the primary degrades silently to local.

The naive form names a single standby:

synchronous_standby_names = 'replica-fra-1'

Enter fullscreen mode Exit fullscreen mode

The problem with naming one standby is obvious. If replica-fra-1 is down or partitioned, your primary blocks on every write until it comes back. You traded read-staleness for write-availability, and you didn't get a discount.

The fix is quorum commit. Postgres 10+ supports:

synchronous_standby_names = 'ANY 2 (replica-fra-1, replica-fra-2, replica-fra-3)'

Enter fullscreen mode Exit fullscreen mode

Read this as: "wait until any 2 of these 3 standbys acknowledge." If replica-fra-1 is down, the other two ack and the commit goes through. You stay durable across two replicas, you stay available as long as two are healthy, and you pay the latency of the second-fastest standby instead of one specific one.

There's a FIRST n (...) form too (strict priority order), but ANY n is the one to reach for. It's the cluster equivalent of a Raft quorum without the consensus protocol.

Per-transaction synchronous_commit: the feature nobody uses

Most teams miss this: synchronous_commit is a session/transaction-scoped GUC. You don't have to run the cluster on one global setting. You can pick the right guarantee per write.

Run the cluster at on (cheap default, ~2 ms commits, replicas may lag a beat). Then, for the specific writes that need read-after-write consistency, escalate inside the transaction:

# checkout flow: must be visible on read replica
# before the redirect to the confirmation page
async def confirm_payment(order_id: str, intent_id: str) -> Order:
    async with db.transaction() as tx:
        # this transaction only, not the whole connection
        await tx.execute(
            "SET LOCAL synchronous_commit = 'remote_apply'"
        )

        await tx.execute(
            """
            UPDATE orders
               SET status = 'paid',
                   stripe_intent_id = $1,
                   paid_at = NOW()
             WHERE id = $2
               AND status = 'awaiting_payment'
            """,
            intent_id,
            order_id,
        )

        # the row visible on every replica before COMMIT returns
        order = await tx.fetchrow(
            "SELECT * FROM orders WHERE id = $1",
            order_id,
        )

    # safe to redirect. confirmation page reads
    # from a replica and will see status='paid'
    return Order.from_row(order)

Enter fullscreen mode Exit fullscreen mode

SET LOCAL is the keyword that matters. It scopes the change to the current transaction. The connection goes back to the cluster default after COMMIT. You don't have to remember to reset it. You don't poison the next query on the same pooled connection.

Now the rest of your traffic (view counts, click events, "user toggled dark mode") runs at cheap on. The one write where stale reads break the product runs at remote_apply and pays 6 ms instead of 2. You bought consistency where it mattered. You didn't pay for it everywhere else.

The same trick applies the other direction. If you have a hot write path that you genuinely don't care about durability for (say a last_seen_at timestamp updated on every API call), drop it to local or off for that one statement:

BEGIN;
SET LOCAL synchronous_commit = 'off';
UPDATE users SET last_seen_at = NOW() WHERE id = $1;
COMMIT;

Enter fullscreen mode Exit fullscreen mode

The cluster keeps its strong default, and this one statement gets to be fast and slightly lossy on purpose.

The failure mode you'll hit first

A synchronous primary with no healthy standby hangs every write. This is not a bug. This is the literal definition of synchronous replication: the primary refuses to acknowledge a commit until its synchronous partner agrees, and if there's no synchronous partner, there's no agreement, so there's no acknowledgement.

You see it as:

  • New connections succeed.
  • SELECT queries succeed.
  • INSERT, UPDATE, DELETE, COMMIT block forever.
  • Your APM dashboard goes red on write p99.

Operators look at the primary and say "Postgres is up, it's healthy, what's the problem." The problem is that synchronous_standby_names = 'replica-fra-1' is set, replica-fra-1 is the only listed standby, it's down, and Postgres is doing exactly what you asked. The mitigations:

  • Use the quorum form (ANY n (...)). Survives any single standby loss.
  • Set up monitoring on pg_stat_replication.sync_state so you find out before users do.
  • For non-critical workloads, accept the on default and don't promise read-after-write consistency on a replica at all.

Don't fix it by editing synchronous_standby_names to an empty string during the incident, by the way. That degrades the cluster to async behind your back, and the runbook tomorrow won't remember why.

Verifying which mode is actually active

Two queries to know. First, what does the primary think the setting is:

SHOW synchronous_commit;
SHOW synchronous_standby_names;

Enter fullscreen mode Exit fullscreen mode

Second, what's the live replication state. Which standbys exist, which are sync, which are async, where are they in WAL:

SELECT
    application_name,
    client_addr,
    state,
    sync_state,
    sync_priority,
    pg_wal_lsn_diff(sent_lsn, write_lsn)   AS write_lag_bytes,
    pg_wal_lsn_diff(sent_lsn, flush_lsn)   AS flush_lag_bytes,
    pg_wal_lsn_diff(sent_lsn, replay_lsn)  AS replay_lag_bytes,
    write_lag,
    flush_lag,
    replay_lag
FROM pg_stat_replication
ORDER BY sync_priority;

Enter fullscreen mode Exit fullscreen mode

sync_state is the column to stare at:

  • sync: a synchronous standby. Primary waits on it.
  • quorum: part of an ANY n quorum. Primary waits on enough of the group.
  • potential: listed in synchronous_standby_names but not currently chosen as sync.
  • async: purely asynchronous. Primary never waits on it.

The three lag columns tell you where each replica is: write_lag is the gap until the standby received the WAL, flush_lag until it fsynced, replay_lag until it applied. replay_lag is the one users feel when they read from a replica.

Alert on replay_lag > 1 second on any standby you serve user reads from. That's not a "warn at 30 minutes" metric. That's a contract.

A decision tree, per write

For each write your service does, ask in order:

  1. Can a stale read on a replica break a user-visible contract? Checkout confirmation, permission grant, "your account is now verified", yes. Use remote_apply, per-transaction with SET LOCAL.
  2. Must this survive a primary crash plus a replica crash? Audit log, payment intent, idempotency key, yes. At least remote_flush. Probably also remote_apply if it's followed by a replica read.
  3. Must this survive a primary crash but a lost replica is acceptable? Most application data. on is fine.
  4. Is durability negotiable for throughput? Last-seen timestamps, view counts, ephemeral session bumps. Use local or off, per-statement with SET LOCAL.

The trap is question 1. Teams skip it because the default of on sounds durable, and they conflate "durable on primary" with "visible on replica." Those are different guarantees on different machines, separated by however much WAL is in flight.

If a checkout-flow read-after-write returns stale because your replica hadn't applied yet, no amount of "the write was durable on the primary" gets you off the hook with the user staring at an empty cart. remote_apply is the answer. Use it where it matters, leave it off everywhere else, and stop blaming the weather.


If this was useful

If picking the right durability and consistency settings per write is the kind of thing you want a full chapter on (not just Postgres, but Mongo write concerns, Cassandra tunables, Redis persistence modes, and the same trade-off shape across each), that's exactly what the Database Playbook is built around. Each store gets its own chapter on consistency knobs, what they cost, and which writes deserve the expensive setting.

Database Playbook: Choosing the Right Store for Every System You Build