Skip to content

fix(logging): keep Redis off the request path for log writes - #1363

Merged
Quick104 merged 3 commits into
mainfrom
perf/opslog-nonblocking-writers
Sep 24, 2026
Merged

Quick104 merged 3 commits into
mainfrom
perf/opslog-nonblocking-writers

Conversation

@Quick104

Copy link
Copy Markdown
Contributor

Problem

Related issue: N/A
Validation tasks: reaches #1217 C2 and #1218 C2 (audit entries and their live delivery; both not run yet). No passed case changes.

When Redis is configured, both database log writers push to Redis on the caller's goroutine. opslog.RedisWriter runs one RPUSH for every captured slog record at the capture level (info by default), and activitylog.RedisWriter runs one for every request through the activity middleware. A logged request therefore waits on two Redis round trips before it returns.

When a push fails, the writer calls slog.Warn. The operational handler is the slog default, so that warning is captured and pushed through the same writer. If Redis refuses connections, each failed push logs another warning and tries another push. One slog.Info never returns, so every request that logs stalls for as long as Redis is down. This affects any deployment with a Redis URL, which includes every multi-node cluster.

Approach

Every node now takes the path that installs without Redis already used. Each node queues operational (app) and activity (audit) entries in its own bounded in-memory buffer, 10,000 entries per stream. A consumer on that node inserts them into Postgres in batches of 100, or every two seconds. logstream.Hub then hands each inserted row to local live-tail subscribers and queues it for a goroutine that publishes it to other nodes through the Redis event bus, as before. Redis is off both the logging path and the persistence path.

  • logstream.Buffer replaces the two copies of MemoryWriter, and logstream.Drain replaces the two batching loops. Write never blocks and never logs. A full buffer drops the entry and counts it in silo_log_writer_dropped_total{stream, reason} (buffer_full).
  • While Postgres is unreachable or refuses work for a passing reason (connection errors, timeouts, restart, failover including writes refused as read-only, overload), Drain retries the batch with backoff from one to ten seconds, and new entries wait in the buffer. Each attempt has a ten-second deadline. When the node is stopping, each batch gets one attempt. A batch that is given up is counted as insert_failed. For comparison, the Redis path made three attempts over about six seconds, and the old in-memory path made one.
  • Log fields carry client input and file system data: request paths, User-Agent headers, file names. Postgres rejects NUL and invalid UTF-8 in text and the \u0000 escape in jsonb, and one such value fails the whole multi-row insert. Both consumers now replace those bytes with U+FFFD before inserting. The old Redis path's JSON round trip replaced invalid UTF-8 as a side effect; a NUL byte failed the batch on every old path.
  • When Postgres still rejects a value (SQLSTATE class 22, for example a client address that is not an inet), Drain inserts that batch one row at a time, so only the rejected rows are dropped and counted. Any other batch the server rejects is dropped at once, so it cannot hold up the stream.
  • opslog.Handler encodes non-scalar attribute values (maps, slices, structs, pointers) to JSON when the record is logged. The consumer builds rows later on its own goroutine, and a caller that changed a logged map in the meantime would race that encode, which is a fatal error for maps. The Redis writer encoded on the logging goroutine, so cluster deployments keep that behavior.
  • Cross-node publishing runs on the hub's own goroutine, with a 1,024-row queue and a two-second deadline for each publish. The consumer never waits on Redis. Rows that do not reach other nodes are counted in silo_log_tail_publish_dropped_total{stream, reason} (queue_full, publish_failed). The hub logs when publishing starts failing and when it recovers, not for each row, because each of those records is itself persisted and published.
  • The opslog consumer logs its own failures with a context flag that opslog.Handler passes to stderr and OTLP only. Without it, a warning about a failed insert would be queued into the next batch, and while Postgres is down the consumer would keep producing entries about itself.
  • Both consumers run on their own context and stop from deferred calls in main after the HTTP servers drain, with a five-second limit on the final flush. The hub then sends its queue, with a two-second limit, before the event bus closes. Records logged during graceful shutdown still reach Postgres and other nodes' live tails.
  • opslog.RedisWriter, activitylog.RedisWriter, both Redis drain loops, and the Redis clients created only for them are removed.

App records also go to stderr and OTLP. Audit entries do not: the request logger skips /api/v2, so an audit entry that is dropped has no other copy. That is why failed inserts are retried and a rejected value costs only its own row.

Alternatives considered:

  • Stop the Redis writers from logging on failure. That ends the recursion, but each logged request still waits on two Redis round trips, and a Redis host that drops packets stalls each write until the dial timeout.
  • Push to Redis from a background goroutine. The shared Redis list only let any node persist any node's entries, which a per-node drain does not need. The tradeoff is crash durability, covered under Risks.
  • Publish to other nodes inline after each insert, with a two-second budget per batch. The first revision of this change did that. With Redis refusing connections or unreachable, one consumer then persisted only 25 to 35 entries per second, so any busy node overflowed its buffer.
  • Retry every failed insert until it succeeds. A batch the server rejects would then hold up its stream for good, so only connection and availability errors are retried.
  • Split a rejected batch row by row without replacing the bytes. The other rows would survive, but the request that sent the bytes would lose its audit entry, which is the entry most worth keeping.
  • Delete the old Redis list keys at startup. During a rolling upgrade, old nodes still push to and drain those lists.

docs/architecture/observability.md records the persistence path, retries, byte replacement, row-by-row fallback, both drop counters, the shutdown order, and the leftover Redis keys.

Before and after

Metric Before After How measured
One slog.Info through the production handler chain, Redis refusing connections Did not return within 2 s in 5 of 5 runs, or within 10 s in one longer run. Over that 10 s the process made 171 failed connection attempts and 6 failed RPUSH calls, each failed push logging another warning. Returned in under 2 ms in every run (32 timed runs: 18 µs to 1.45 ms; timing depends on host load), with 0 Redis operations TestOperationalLoggingReturnsWhileRedisIsDown; Redis operations counted from silo_dependency_operations_total
Redis commands per logged request, Redis healthy 2 (RPUSH ×2); 200 over 100 requests 0; 0 over 100 requests TestLoggedRequestIssuesNoRedisCommands: 100 requests through the activity middleware whose handler logs at info, against a stub Redis server that counts every command
Log entries one consumer persists per second, Redis refusing connections or unreachable None, from reading the code: each RPUSH fails, so no entry reaches the Redis list that the consumer drains Median 11,900 entries/s with Redis refusing connections and 11,900 with it unreachable, against 11,700 with no event bus (9 runs each; single runs ranged from 5,300 to 17,800) 2,000 queued app entries drained into the test database through a real Redis event bus pointed at a refused port and at a non-routable address, on a shared host at load average about 100
Rows kept from a 5-row activity batch holding a 0xFF User-Agent, a NUL in the path, and one client address that is not an inet 0 of 5: Postgres rejects the statement (SQLSTATE 22021) and the batch is dropped 4 of 5: the bytes become U+FFFD and only the bad address is dropped TestConsumerKeepsEntriesBesideInvalidTextDB (activitylog; the opslog test does the same for message, component and attrs), run on the previous revision of this branch for the before value
BenchmarkLoggedInfo allocations 41 allocs/op, 2,418 B/op 6 allocs/op, 696 B/op 5 runs each, one process per run
BenchmarkLoggedInfo time 43.9 to 46.9 µs/op 2.14 to 2.92 µs/op Same runs, before and after interleaved on a shared 48-core host (load average about 100)

The before numbers come from the base commit with the same tests adapted to the old wiring, where configureOperationalLogging took a Redis config and the activity writer was built inline in main. Neither that harness nor the throughput harness is committed. The throughput and benchmark rows were measured after the rebase, on a busy host. Earlier runs at load average 15 to 20 gave 20,100 to 26,600 entries/s with Redis refused or unreachable against 19,400 to 23,000 with no event bus, and 27.6 to 34.1 µs/op before against 1.46 to 1.56 µs/op after for BenchmarkLoggedInfo.

The base commit also loses the invalid-byte batch above: its Redis JSON round trip replaced the 0xFF but not the NUL, and the bad address failed the batch on every path (from reading the code). In the after benchmark the consumer cannot reach Postgres, so the buffer fills and most iterations take the drop path, which costs the same channel select as a successful send. Benchmark allocations count every goroutine.

Encoding non-scalar attributes at log time costs 2 allocations, 33 bytes, and about 0.1 µs for each such attribute, such as an error (a one-off benchmark of the handler alone against the previous revision). BenchmarkLoggedInfo logs scalars only, so its numbers do not include this.

Total Redis traffic falls too, based on reading the code rather than an end-to-end count. Before, each logged request cost two RPUSH calls on the request goroutine, each consumer polled with EVALSHA every two seconds, and each persisted row cost one PUBLISH. After, each persisted row still costs one PUBLISH, sent from the hub's goroutine.

Validation

All checks below ran on the branch after rebasing onto the current base. The rebase had no conflicts, and the branch touches no generated artifacts.

  • make embed-stub, go build ./..., gofmt -l . (empty), go vet ./...: pass.
  • make lint-changed: 0 issues.
  • GOFLAGS=-p=6 make test-go: 159 of 160 packages pass. internal/policy failed TestResolveViewerScopeParity once, on a 25 ms policy-evaluation timeout while the host load average was above 150. That package imports none of the packages this branch changes, and the test and the whole package pass when run alone.
  • Database-backed tests with SILO_TEST_DATABASE_URL set, after applying migrations: ./cmd/silo, ./internal/opslog/..., ./internal/activitylog/..., ./internal/logstream/..., ./internal/api, and the Log|Audit|Operational|Socket tests in ./internal/apiv2 and ./internal/api/handlers: pass.
  • go test -race on ./internal/logstream, ./internal/opslog and ./internal/activitylog (with the database), and on the two pipeline tests in ./cmd/silo: pass.
  • make verify-settings-bindings-all verify-playback-fixtures verify-route-inventory verify-migration-ledger verify-scenario-catalogs verify-offline-routes verify-apiv2-openapi verify-apiv2-contract verify-apiv2-fixtures verify-local-paths and TestCommittedArtifactMatchesRouter: pass.
  • The web and migration gates do not apply; neither area changed.
  • New tests:
    • logstream buffer and drain: a full buffer drops and counts without blocking; batching by size and interval; the final flush keeps context values without the cancellation, and every attempt has a deadline; a batch that fails twice with a refused connection is persisted on the third attempt with nothing counted as dropped; a batch the server rejects as a whole is dropped after one attempt; a batch with one rejected value keeps the other rows and counts one drop; a batch waiting between retries gets one last attempt when the drain stops; a hung insert is cut off by the deadline and retried; error classification, including read-only refusals and the errors a real pgxpool returns for a refused connection and a closed pool.
    • logstream text: invalid UTF-8 and NUL become U+FFFD, clean text is returned without allocating, and \u0000 escapes are replaced without touching an escaped backslash followed by u0000.
    • logstream hub: PublishAppends returns without waiting while every publish hangs, local subscribers still receive rows, and the queue overflow is counted; queued rows reach the event bus in order before Close returns; a failing event bus is logged once, not per row.
    • opslog: a stopping consumer that cannot reach Postgres counts the dropped batch, reports it on the console, and writes nothing back into the pipeline; a logged map and slice changed after the call keep their logged values; a value JSON cannot encode is kept as text.
    • opslog and activitylog (database-backed): a consumer stopped with 60 entries buffered persists all 60 and delivers them to a local live-tail subscriber; a batch with invalid bytes and one bad client address keeps every row but the bad address. Both invalid-byte tests fail on the previous revision (0 rows kept). In opslog, a consumer persists 1,000 entries in 54 to 59 ms while every cross-node publish hangs (77 to 133 ms after the rebase, on a busier host); the first revision of this change took 26 s.
  • CI's Go job does not set SILO_TEST_DATABASE_URL for these packages, so the database-backed consumer tests skip there.

Risks

  • Upgrade: the new code never reads the ops_log:buffer and activity_log:buffer Redis lists. An old node drains both lists once, when its shutdown begins, and stops as soon as they are empty. It keeps pushing for the rest of its shutdown: the HTTP drain (up to 30 s), playback cleanup, and the remaining deferred stops. During a rolling upgrade, other old nodes still drain those entries. The entries the last old node logs during its own shutdown stay in Redis and never reach Postgres, and so does any backlog it had not drained, for example after Postgres trouble. On a single-node upgrade that covers the whole shutdown of the old node. App entries among them also went to stderr and OTLP; audit entries have no other copy. The keys have no TTL. Release notes should say: once no pre-upgrade node is running, run DEL ops_log:buffer activity_log:buffer.
  • Crash durability: a Redis list outlived the process, so another node persisted entries a crashed node had already pushed. Now a node that dies loses what is still in its buffer, normally under two seconds of entries, or up to 10,000 per stream while Postgres is down or inserts fall behind. That includes the record log.Fatalf writes just before the process exits. Before, the synchronous RPUSH kept that record for another node, or the restarted node, to persist, so the reason for a fatal exit appeared in the admin log view. Now it reaches stderr and OTLP only. Graceful shutdown flushes the buffer.
  • Postgres outages: each node holds up to 10,000 entries per stream while it retries, then drops new entries and counts them as buffer_full. The Redis path had no size limit on its list but dropped each batch after three attempts over about six seconds. Dropped audit entries are lost for good.
  • Rejected values: a row whose value Postgres still rejects after byte replacement, such as a client address that is not an inet, is dropped and counted on its own. A batch with such a row costs up to 100 single-row inserts. A NUL or invalid byte in a stored entry now shows as U+FFFD.
  • Duplicate rows: if the connection drops after an insert commits but before the reply arrives, the retry inserts that batch again. The Redis path's retries behaved the same way.
  • Live tail: while Redis is down, other nodes' live tails miss this node's rows. The rows are still in Postgres and the admin log lists. The hub publishes one row at a time, so a node that persists more rows per second than its Redis round-trip time allows drops some cross-node tail rows (counted) instead of slowing persistence. That limit is an estimate, not a measurement. Publishing queued rows in one pipelined round trip would lift it; that needs a batch publish on the event bus and is left for a follow-up.
  • Shutdown with Postgres hung: the final insert attempt can hold a connection for its ten-second deadline, which can delay closing the pool by that long after the five-second flush limit.
  • Proxy and transcode nodes now insert their own log rows. They already ran a consumer with a database pool, so this adds no new dependency.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.

AI Disclosure

  • Harness: Claude Code, running in T3 Code

  • Tool(s): Claude Code built-in tools (shell, file read/edit, Workflow subagents), GitHub CLI (gh)

  • Model(s): claude-opus-5-5[1m] for the main session and all subagents

  • Involvement: Fully AI-generated; maintainer review pending

  • Adversarial review: a separate reviewer subagent (claude-opus-5-5) reviewed the full diff twice. Each round re-ran the before and after measurements in scratch worktrees of the base commit and the branch, and checked shutdown order, the multi-node live tail, the validation-task line, and the lint and test gates.

    Round 1 reviewed the first revision. It confirmed the recursion hang on the base commit (171 connection attempts and 6 RPUSH in 10 s), both pipeline tests failing there and passing on the branch, and that revision's 2 → 0 Redis-command and 41 → 13 allocation numbers. Findings and resolutions:

    1. Major: a Redis outage still throttled persistence. The consumer published to other nodes inline under a two-second budget per batch, so with Redis refused or unreachable it persisted 25 to 35 entries per second. Fixed: publishing moved to the hub's goroutine behind a bounded, counted queue. New hub tests and a database-backed test cover it.
    2. Major: a failed batch insert was dropped on the first attempt, a durability loss for every Redis-configured cluster, where the Redis path retried. Fixed: connection and availability errors are retried with backoff while the node runs, and a stopping node makes one attempt. New drain tests cover each case.
    3. Major: the claim that stderr and OTLP receive every record is false for audit entries, which have no other copy for /api/v2 requests. Fixed in the metric help, the doc, and this description.
    4. Minor: the upgrade risk understated which entries stay in Redis. Reworded above, with the DEL step for release notes and in the doc.
    5. Minor: a log.Fatalf reason no longer reaches the database log. Added to Risks and the doc.
    6. Nit: steady-state inserts had no deadline. Fixed: each attempt has a ten-second deadline.
    7. Nit: the after latency for slog.Info did not reproduce on a loaded host (52 µs to 1.45 ms). The table now gives a bound with the observed range.
    8. Nit: the disclosure fields did not use the template values. Fixed here.

    Round 2 reviewed the second revision. It reproduced every number in the table: slog.Info with Redis refused went from no return within 2 s (20 Redis operations) to 472 µs (0), a logged request from 200 to 0 Redis commands over 100 requests, BenchmarkLoggedInfo from 41 to 6 allocs/op, and persistence with Redis refused or unreachable at about 10,600 entries/s against 12,300 with no bus, on a busier host. Findings and resolutions:

    1. Major: removing the Redis JSON round trip also removed its replacement of invalid UTF-8, so one unauthenticated request with a 0xFF byte in its path or User-Agent made Postgres reject the whole batch, losing up to 100 other audit entries. The reviewer reproduced it against the test database (0 of 3 rows kept). Fixed: both consumers replace invalid UTF-8 and NUL bytes in text fields and \u0000 escapes in attrs JSON, and a batch with a rejected value (class 22) is inserted row by row. New database-backed tests keep 4 of 5 rows where the previous revision kept 0.
    2. Minor: KindAny attributes were encoded on the consumer goroutine, up to seconds after the call, so a caller that changed a logged map could crash the node. Fixed: the handler encodes them when the record is logged. New handler tests cover it; the cost is measured above.
    3. Nit: the live tail publishes one row at a time, which caps cross-node tail throughput. Left as a follow-up under Risks, because batching needs a new event bus method or a change to the published envelope that older nodes read.
    4. Nit: the description claimed failover coverage, but a write refused as read-only (25006) after a switchover was not retried. Fixed: 25006 is retried.
    5. Nit: the Involvement field claimed human verification, the adversarial review covered one round, and the 100-request figures named a test that served one request. Fixed: Involvement states that verification is pending, this section covers both rounds, and the committed test now serves 100 requests.

🤖 Generated with Claude Code

Quick104 and others added 3 commits September 24, 2026 02:56
With Redis configured, every captured slog record and every request
through the activity middleware ran a synchronous RPUSH on the caller's
goroutine. When the push failed, the writer logged a warning through the
slog default, which is the operational log handler, so the warning was
pushed through the same writer. While Redis refused connections one
slog.Info never returned and every request that logged stalled.

Every node now uses the path single-node installs already had: operational
and activity entries go into a bounded in-memory buffer
(logstream.Buffer), and a consumer on the same node inserts them into
Postgres in batches and publishes each row to the admin live tail.
Writers never block or log. A full buffer or a failed batch insert is
counted in silo_log_writer_dropped_total{stream,reason}.

The opslog consumer's own warnings go to stderr and OTLP only, so a
failing batch cannot queue entries about itself. Cross-node publishes for
a batch share a two-second deadline, so an unreachable Redis cannot stall
the consumer row by row. The consumers outlive appCtx and flush from
deferred calls in main, so records logged during graceful shutdown are
persisted. The Redis writers, the Redis drain loops and their dedicated
Redis clients are removed.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
… the drain

Review of the first revision found that a Redis outage still throttled
Postgres persistence and that a Postgres blip dropped whole batches.

The consumer published each inserted row to other nodes inline, under a
two-second budget per batch. With Redis refusing connections or
unreachable, one consumer persisted only 25 to 35 entries per second, so
any busy node overflowed its buffer. logstream.Hub now hands rows to local
subscribers inline and queues them (1,024 rows) for its own goroutine,
which publishes to the event bus with a two-second deadline per publish.
The consumer never waits on Redis. Rows that miss other nodes' live tails
are counted in silo_log_tail_publish_dropped_total{stream,reason}, and the
hub logs only when publishing starts failing and when it recovers. main
closes the hub after the log consumers flush and before the event bus
closes.

A failed batch insert was dropped on the first attempt. logstream.Drain
now retries connection and availability errors with backoff from one to
ten seconds while the node runs, so the buffer holds entries through a
Postgres restart or failover. A batch the server rejects is dropped at
once, a stopping node makes one attempt per batch, and every attempt has
a ten-second deadline.

The metric help and the observability doc no longer claim that stderr
and OTLP receive every record: audit entries have no other copy. The doc
also covers the lost log.Fatalf record on exit and the leftover Redis
list keys from earlier versions.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Without the Redis JSON round trip, raw strings reached the multi-row
INSERT, so one request with a 0xFF byte in its path or User-Agent made
Postgres reject the whole batch and dropped up to 100 other audit
entries. Both consumers now replace invalid UTF-8 and NUL bytes in text
fields, and \u0000 escapes in attrs JSON, with U+FFFD. When Postgres
still rejects a value (SQLSTATE class 22, such as a client address that
is not an inet), the drain inserts that batch one row at a time so only
the rejected rows are dropped and counted.

opslog.Handler now encodes non-scalar attribute values when the record
is logged. The consumer encoded them seconds later on its own goroutine,
so a caller that changed a logged map could race that encode.

A write refused as read-only (25006) after a switchover is now retried.
The request pipeline test serves 100 requests.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Quick104 has reached the 50-credit limit for trial accounts. To continue receiving code reviews, upgrade your plan.

@coderabbitai

coderabbitai Bot commented Sep 24, 2026

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

Next included review available in 1 minute.

Check out review usage here.

View limit details

Limit details: You’ve used all 2 included reviews currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Advanced

Run ID: ec0f07ae-b8ae-454e-adc2-84005e7e2021

📥 Commits

Reviewing files that changed from the base of the PR and between d4e35ba and eff92f2.

📒 Files selected for processing (24)
  • cmd/silo/log_pipeline_test.go
  • cmd/silo/main.go
  • docs/architecture/observability.md
  • internal/activitylog/consumer.go
  • internal/activitylog/consumer_db_test.go
  • internal/activitylog/entry.go
  • internal/activitylog/writer_memory.go
  • internal/activitylog/writer_redis.go
  • internal/logstream/buffer.go
  • internal/logstream/buffer_test.go
  • internal/logstream/drain.go
  • internal/logstream/drain_test.go
  • internal/logstream/hub.go
  • internal/logstream/hub_test.go
  • internal/logstream/text.go
  • internal/logstream/text_test.go
  • internal/opslog/consumer.go
  • internal/opslog/consumer_db_test.go
  • internal/opslog/consumer_test.go
  • internal/opslog/entry.go
  • internal/opslog/handler.go
  • internal/opslog/handler_test.go
  • internal/opslog/writer_memory.go
  • internal/opslog/writer_redis.go

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-24T03:59:32.073905Z eff92f2 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@Quick104
Quick104 merged commit 1a23d4c into main Sep 24, 2026
10 checks passed
@Quick104
Quick104 deleted the perf/opslog-nonblocking-writers branch September 24, 2026 12:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant