← Back to blog

DDIA Chapter 8: The Trouble with Distributed Systems — How ClawMetry Watches Agents It Cannot Trust

· 9 min read · By Vivek Chand

Chapter 8 of Designing Data-Intensive Applications is titled “The Trouble with Distributed Systems.” It is Kleppmann’s most pessimistic chapter, and deliberately so. The thesis is that distributed systems fail in ways that are fundamentally different from a single computer: partial failures, where some components work and others don’t, with no clear signal about which is which. You send a request and you don’t know whether it was received, executed, or dropped. A process can be paused for 30 seconds and resume as if nothing happened. Two machines can disagree on what time it is.

Reading Chapter 8 made me realize that ClawMetry is itself a distributed system trying to observe a distributed system. And every hard problem Kleppmann describes — liveness detection, heartbeat timeouts, process pauses, the observer that cannot trust its own network — we had either already hit, or were about to.

Here are the five Chapter 8 concepts that shaped real decisions in ClawMetry’s code, in the order we encountered them.

Concept 1: Partial failures

In a single computer, things either work or they crash. In a distributed system, they can half-work: a process is running but responding slowly, a network link is up but dropping packets, a node is reachable from some machines and not others. Kleppmann calls these partial failures, and argues they are the fundamental reason distributed systems are hard to reason about.

An AI agent fleet is a distributed system. When a team runs three Claude Code sessions on a Mac, two Codex sessions on a Linux box, and an OpenClaw orchestrator on a VPS, every one of those is a separate process on a different machine (or a different user environment on the same machine). They share no memory. They don’t coordinate. ClawMetry’s multi-node fleet view has to tell you which of these is running, which is stuck, and which has silently stopped — without any cooperation from the agents themselves.

The challenge is that a silent agent looks exactly like a healthy one until you have external evidence to the contrary. This is Chapter 8’s core puzzle: a node that stops sending messages might be dead, or it might just be on a slow network. You cannot distinguish them from the observer’s side alone.

Our answer is a two-tier liveness model:

  • Daemon heartbeat: the sync daemon pushes an encrypted snapshot to ingest.clawmetry.com at the end of every ingest cycle (every ~15 seconds). If the cloud hasn’t received a snapshot for a node in N seconds, that node appears “offline” in the fleet view. This is a standard distributed-systems timeout-based failure detector — imperfect, but practically useful.
  • Stalled ingest flag: CLAWMETRY_STALLED_INGEST_SECS=3600. The daemon reports itself as stalled if it hasn’t completed a full ingest cycle in one hour. This catches the case where the daemon is running (heartbeat arrives) but not ingesting (a source is hung, the DuckDB lock is contested, the gateway WebSocket is reconnecting forever). Stalled is worse than offline because it looks fine from the outside.

These are the two signals the fleet view shows side by side. A node with a recent heartbeat but a stalled ingest flag is the most dangerous state: the agent is running, the daemon is running, but the data you’re reading is hours old.

Concept 2: Unreliable networks and full-state snapshots

Chapter 8 spends time on what happens when network messages are delayed, reordered, or duplicated. The key insight is that you cannot distinguish a slow network from a dead recipient: a request with no response could mean the request was lost, the recipient died before processing it, the response was lost, or the response is just slow. The timeouts you set determine how long you wait before giving up, but you can never be certain.

This directly shaped one of ClawMetry’s most important architectural decisions: full-state snapshots instead of delta streams for cloud sync.

An obvious approach would be for the daemon to push deltas — “here are the new events since the last snapshot” — and for the cloud relay to stitch them into a full state. This would be more bandwidth-efficient. We didn’t do it. Here’s why.

If a delta push fails (network drop, proxy timeout, the cloud ingest service restarts), the cloud relay is now missing a chunk of history. On the next push, the daemon doesn’t know whether the previous delta arrived. It would have to either re-send potentially large batches of overlapping data or risk a gap. The state machine for tracking what the cloud has vs. what the daemon has is a classic distributed systems coordination problem, and those are exactly the problems Chapter 8 warns you to minimize.

Instead, every daemon push is a complete, self-contained AES-256-GCM encrypted snapshot of the current state. If a push is dropped, the next one (15 seconds later) carries everything the cloud needs. There is no gap, no sequence number to track, no “did you get my last message?” The tradeoff is bandwidth: each push is larger than a delta would be. For the data volumes of a typical agent session (a few hundred KB of events per sync cycle), this is entirely worth it. The simplicity of the stale-snapshot model more than pays for the bandwidth overhead.

# clawmetry/sync.py — every push is a full snapshot
# If the last push was dropped, this one carries the same data plus new events.
# The relay does not need to stitch anything.
def _push_encrypted_snapshot(config, conn):
    payload = _build_full_state_snapshot(conn)
    ciphertext = _aes_gcm_encrypt(payload, config.cloud_key)
    _push_to_relay(ciphertext)  # fire-and-forget; next cycle fixes any drop

This is DDIA Chapter 8’s advice in practice: when in doubt, design for idempotent full-state operations rather than stateful delta protocols. The partial failure where a delta was dropped is impossible to recover from cleanly; the partial failure where a full snapshot was dropped is transparently self-healing on the next cycle.

Concept 3: Process pauses and the heartbeat starvation incident

Chapter 8’s section on process pauses is the one I return to most often. Kleppmann describes how a process can be stopped mid-execution — a GC pause, a VM migration, a hypervisor doing maintenance — and resume as if no time has passed, while the rest of the system has moved on. A process that holds a lease or expects to send a heartbeat every N seconds can silently drop its heartbeat for 30 or 60 seconds and not realize anything went wrong.

We hit this exact failure mode in ClawMetry, documented in our internal RCA from July 30, 2026.

The sync daemon runs a main loop that fires every 15 seconds. At the end of each loop iteration, it pushes the encrypted snapshot to the cloud relay. The relay is also responsible for answering pending queries from the browser — transcript loads, Brain time-window fetches, approval states — but only after a fresh heartbeat confirms the daemon is alive.

What happened: a user connected ClawMetry for the first time on a machine with 465 unread agent sessions. The “first-run ingest” pass processed all 465 session files in one main-loop iteration. That pass took 2 minutes and 40 seconds. During those 2 minutes and 40 seconds, no heartbeat was pushed to the cloud relay. Every pending browser query — transcript reads, Brain event streams — sat in the relay’s pending_queries queue until the browser gave up after its 30-second timeout. The user saw a blank screen for most of that window.

This is Kleppmann’s process-pause problem exactly. The daemon wasn’t dead. It wasn’t slow in a way the OS or the network would surface as an error. It was simply busy — stuck in a CPU-bound loop — and from the cloud relay’s point of view, indistinguishable from a dead node until the ingest pass completed and the heartbeat finally arrived.

The fix was straightforward once we named it correctly: any ingest pass that might run long must call _ingest_keepalive_heartbeat(config) between items. This pushes a lightweight heartbeat snapshot mid-pass so the relay knows the daemon is still alive and can drain pending queries without waiting for the full ingest to complete.

# clawmetry/sync.py — added after the July 2026 RCA
def _ingest_family_sessions(config, conn, sessions):
    for i, session_path in enumerate(sessions):
        _ingest_one_session(conn, session_path)
        # Flush a keepalive every 50 sessions so the relay stays unblocked.
        # Without this, a 465-session first-run blocked heartbeats for 2m40s.
        if i % 50 == 0:
            _ingest_keepalive_heartbeat(config)

The lesson from Chapter 8 is that you cannot fix process pauses by making the process faster. You fix them by making the system tolerant of a process being temporarily unresponsive. For us, that meant pushing heartbeat state out of the main loop completion and into a periodic check mid-pass. The 50-session cadence means the worst-case heartbeat gap is now under 10 seconds even on the largest first-run ingest.

Concept 4: Fencing tokens and stale daemon lock detection

Chapter 8 introduces “fencing tokens” as the solution to a classic distributed problem: a process holds a lease, gets paused (see above), and resumes after the lease has expired. Without a fencing mechanism, the paused process can resume and continue acting as if it still holds the lease, conflicting with whoever took it over.

The ClawMetry daemon writes a lock file to ~/.clawmetry/daemon.lock containing its PID and a timestamp of its last heartbeat. If a second daemon starts, it checks the lock file. If the lock file’s timestamp is fresher than CLAWMETRY_LOCK_STALE_SECS (default: 900 seconds, 15 minutes), the second daemon exits: the first is considered alive. If the timestamp is older than 900 seconds, the second daemon takes over: the first is considered dead or stuck.

This is a timeout-based fencing mechanism. The 900-second threshold is the heartbeat starvation budget: even during a large first-run ingest (now bounded to <10s between keepalives), the daemon will never go 900 seconds without updating its lock timestamp. So a lock older than 900 seconds is a reliable signal that the previous daemon process is gone.

CLAWMETRY_LOCK_STALE_SECS=900  # how long a holder may miss its heartbeat
                                # before the next start takes over
                                # (env var, documented in CLAUDE.md)

The fencing analogy is not perfect — we don’t use incrementing token numbers as Kleppmann describes, and DuckDB’s file-level write lock provides an additional layer of protection against two daemons writing simultaneously. But the design intent is the same: a stale lease holder must not block the system indefinitely. The timeout is the fencing mechanism.

One important detail: when a new daemon takes over a stale lock, it does not immediately overwrite or delete the old lock file’s contents. It first logs the takeover event (with the old PID and timestamp) so a human can investigate whether the previous daemon died due to a crash or due to a hang. The takeover is an observable event, not a silent override.

Concept 5: Truth is defined by the observer, not the observed

This is Chapter 8’s most philosophical point: in a distributed system, a node cannot know if other nodes have declared it dead. The network can partition, and the node continues operating under the belief that it is the leader, unaware that a quorum has elected a replacement. “The truth is defined by the majority,” Kleppmann writes — and a minority-side node’s belief about its own state is simply not authoritative.

For AI agent observability, this has a direct and uncomfortable implication: you cannot trust the agent’s self-report.

An agent that is stuck in a loop does not know it is stuck. It has no introspective signal that it has called the same tool 40 times in the last 5 minutes. Its last message to the user may be “working on it” or “retrieving data.” From inside the process, everything is proceeding normally — the model is computing, the tool calls are returning (slowly, perhaps), the loop will surely terminate soon. The agent’s self-report says healthy. The external view says stuck.

This is why ClawMetry reads the agent’s filesystem and gateway data directly, rather than relying on an in-process SDK or a callback from the agent. The sync daemon reads session transcripts from ~/.claude/projects/, ~/.openclaw/agents/, and the other runtime-specific directories. It connects to the OpenClaw gateway WebSocket directly. It does not ask the agent to report its state. The agent’s JSONL transcript is a ground-truth record that the agent itself cannot corrupt or selectively omit.

Local-first compute is the Chapter 8 answer to self-reporting bias. When ClawMetry runs on the same machine as the agent, it reads the same files the agent writes. There is no network hop, no serialization, no agent middleware that could lie (or crash). The daemon is a silent, independent witness to the same ground truth the agent operates on.

The trajectory detectors in clawmetry/detectors.py implement exactly this: they read the JSONL transcript and count tool-call sequences, repeated patterns, and time-between-events. No agent cooperation required. An agent stuck in a loop fires the no_progress detector whether or not the agent knows it is looping, and regardless of what the agent’s last user-visible message said.

# clawmetry/detectors.py (simplified)
# The agent never calls this. The daemon reads the transcript and runs it.
def detect_no_progress(session_events, thresholds):
    tool_calls = [e for e in session_events if e["type"] == "tool_use"]
    recent = tool_calls[-thresholds.noprog_window:]
    unique_tools = len(set(c["tool"] for c in recent))
    if len(recent) >= thresholds.noprog_min and unique_tools <= 2:
        return Incident(kind="no_progress", severity="warning", ...)

The agent cannot suppress this. It cannot suppress it by design. Chapter 8’s point — that the observed node’s self-belief is not authoritative — is the reason the entire ClawMetry architecture is external-read-first.

Bonus: Unreliable clocks in multi-runtime fleets

Chapter 8 has a substantial section on clock unreliability. Time-of-day clocks jump forward or backward under NTP, and two machines can legitimately disagree on the current time by hundreds of milliseconds or more. Monotonic clocks are reliable for measuring elapsed time within a process, but they are not comparable across machines.

This is a real problem in multi-runtime agent fleets. A session transcript from a laptop with NTP drift will have event timestamps that are, say, 300ms behind the daemon’s wall clock. When the daemon joins events from a Claude Code session on the laptop with events from an OpenClaw gateway on a VPS, the two clocks are not synchronized. Sorting interleaved events by timestamp produces a subtly wrong ordering.

Our current approach:

  • Intra-session ordering uses sequence, not wall-clock. Within a session, events are ordered by their position in the JSONL file (line number), not their timestamp field. The agent writes events in causal order; the JSONL file captures that order. We use timestamps only for approximate cross-session sorting and time-range queries, where a few hundred milliseconds of clock skew does not change the answer.
  • The daemon stamps its own ingestion time alongside the event timestamp. Every row in DuckDB carries both event_ts (from the transcript) and ingest_ts (from the daemon’s clock at ingest time). The fleet “last active” time shown in the UI is ingest_ts, not event_ts, because the daemon’s clock is local and consistent.

This is not a complete solution to the clock problem — Kleppmann is right that it has no complete solution short of GPS-synchronized hardware clocks. It is a pragmatic approximation that works for the query shapes agent observability actually uses.

The full Chapter 8 map

DDIA Ch8 concept ClawMetry decision Where in the code
Partial failures Two-tier liveness: daemon heartbeat + stalled-ingest flag clawmetry/sync.py, /api/nodes
Unreliable networks Full-state snapshots per sync cycle, not delta streams _push_encrypted_snapshot() in sync.py
Process pauses Mid-pass keepalive heartbeat (every 50 sessions); never starve the relay _ingest_keepalive_heartbeat() in sync.py
Fencing tokens Stale daemon lock: 900s timeout before takeover; takeover is logged CLAWMETRY_LOCK_STALE_SECS
Observer vs. self-report Read filesystem + gateway directly; no agent SDK required clawmetry/sync.py adapters, detectors.py
Unreliable clocks Intra-session ordering by JSONL sequence; dual timestamps (event_ts + ingest_ts) clawmetry/local_store.py schema

What we gave up

Honest accounting:

  • Fine-grained liveness. The timeout-based failure detector (no heartbeat for N seconds → offline) is imprecise by design. A node that is simply behind a slow network link will appear offline until its heartbeat arrives. We accept false-positive “offline” states rather than adding the complexity of quorum-based consensus. The fleet view shows “last seen X minutes ago” rather than a binary alive/dead state.
  • Exactly-once delivery of snapshots. Full-state pushes are idempotent, so a dropped snapshot is not a data-loss event. But it does mean the cloud relay may serve data that is one or two snapshot cycles stale (30–45 seconds old) during a network blip. We show a “last updated” timestamp in the cloud UI so the user knows exactly how fresh their data is.
  • Cross-machine causal ordering. Two events on two different machines, at approximately the same wall-clock time, are not guaranteed to be ordered correctly in the DuckDB store. For the query shapes we care about (cost per session, tool-call sequences within a session, fleet-level aggregations), this is acceptable. It would not be acceptable for financial audit logs or compliance records.

The meta-lesson from DDIA Chapter 8

Kleppmann’s Chapter 8 is an argument for humility. Distributed systems fail in ways that look like normal operation. A node can be alive but paused. A network can be up but lossy. A clock can be running but wrong. The book’s advice is not to avoid distributed systems — that’s not an option — but to design for partial failure as the normal case rather than the edge case.

For ClawMetry, this translates into a few concrete postures:

  • Assume the daemon will pause. Every long-running pass must yield. Heartbeats must be independent of main-loop completion.
  • Assume pushes will be dropped. Every push must be idempotent and self-contained. No delta state to synchronize.
  • Never trust an agent’s self-report. Read the ground truth from the filesystem. The agent’s last user-visible message is a belief, not a fact.
  • Accept approximate answers for distributed state. Clock synchronization is hard. Liveness detection has false positives. Show confidence levels and “last seen” times rather than falsely precise statuses.

The deepest irony of building an observability tool is that the observer is itself a distributed system subject to all the same failure modes it tries to surface in its subjects. ClawMetry can tell you that your agent is stuck in a loop. DDIA Chapter 8 tells us to make sure ClawMetry is never the reason you can’t find out.

ClawMetry fleet view showing multi-node status and last-heartbeat timestamps
The ClawMetry fleet view: last heartbeat, stalled-ingest flag, and liveness status for each node — the two-tier failure detector in production

Watch your agent fleet across machines — without trusting their self-reports

ClawMetry reads filesystem + gateway data directly. No SDK, no code changes, no agent cooperation required. Free, open source, local-first.

Get ClawMetry
Cookie preferences