Building Pulse: An Event Ingestion and Analytics Backend That Survives Production

2026-12-03来源 dev.toEnglish
Building Pulse: An Event Ingestion and Analytics Backend That Survives Production

Pulse is a Go service I designed and built at Flabs, where I've been a backend engineering intern since June 2026. Flabs builds a CRM for diagnostic labs across India. Pulse serves every announcement, survey, ideas board and roadmap inside that CRM, records every interaction with them, answers analytics queries over that data, and also runs live location tracking for field staff.

TL;DR. Problem: our announcement tool gave us a view count and nothing else. Solution: a modular Go service with three stores, each with one job: MongoDB for content, Redis Streams as an ingest buffer, ClickHouse for analytics. The request never waits for the database. Impact: over 80k events/sec accepted at a p99 of about 4ms in load tests, exact numbers on every dashboard, and a second product (live location) added as one more module.

The Problem

We used Frill for announcements. Publishing one got us a view count and nothing else. We couldn't tell who watched it, for how long, which slide of a carousel lost them, or whether they clicked through. We also couldn't target content by our own lab data (plan, region, modules), because a third-party widget doesn't know who our labs are. That was the deciding argument for building instead of buying.

Functional requirements

  • Serve announcements, surveys, an ideas board and a roadmap to an in-app widget, targeted by lab, role, region, plan and modules.
  • Record every interaction (impression, slide view, dwell time, read completion, click, vote, survey answer) as an immutable event.
  • Give the product team a dashboard to slice that data.

Non-functional requirements

  • The tracking call must never slow the CRM down.
  • No event may be lost or counted twice. Browsers retry, and beacons sometimes fire twice.
  • Numbers must be exact. If two panels disagree, nobody trusts either.
  • A lab must never see another lab's data.

Phase 1: The Shape of the System

Pulse architecture
One Go service, three stores, and a write path that never waits for the database.

Pulse is a single Go service built as a modular monolith in the ports-and-adapters style. Each domain is a folder with its own interfaces, and domain code never imports a database driver. That made the ingest pipeline testable against in-memory fakes in milliseconds, which paid off on every bug fix below.

Flabs' main backend is a Node.js monolith, and adding Pulse to it was the obvious default. I rejected it for isolation: tracking traffic is bursty, and a burst should never compete with billing for the same event loop. Go also made the worker pool trivial and shipped as one static binary of about 15MB.

Each store has exactly one job:

Store Job Why this one
MongoDB Content and targeting rules Nested, changing shapes; the CRM already uses it, so Pulse reads real lab data
Redis Streams Ingest buffer Sub-millisecond appends, consumer groups with acknowledgements
ClickHouse Analytics Columnar storage for an append-only firehose, materialized views that pre-aggregate on insert

I turned down a few obvious alternatives. Postgres with TimescaleDB would have handled our volume, but ClickHouse's rollup engine and compression won. Kafka would have been a large system to run for a load Redis Streams handles fine, and the buffer sits behind an interface if we ever need to swap it.

Phase 2: An Ingest Path That Never Waits

The write path
The handler replies in milliseconds. Dedup, batching and the insert all happen after the client has gone.

The handler validates a batch of events, appends it to a Redis Stream and replies 202 Accepted. A worker pool reads from the stream, removes duplicates and inserts into ClickHouse in batches.

Writing straight to ClickHouse from the request looks simpler, and it's wrong for two reasons. If ClickHouse is slow, the CRM gets slow. And ClickHouse handles lots of tiny inserts badly: every insert creates a part on disk, and thousands of them end in Too many parts errors. Because our worker reads from a buffer, it always inserts hundreds of events at once. The buffer doubles as the batching layer.

Duplicates are caught twice: a Redis check on each event ID in the hot path, and a ReplacingMergeTree table keyed on that ID as a backstop. In the load test I sent one fixed event ID in every batch, thousands of times, and ClickHouse kept exactly one row.

Bottleneck: 500 round-trips to say "no"

The first worker drained only about 10k events/sec. Profiling showed why: the dedup check made one Redis EXISTS call per event, so a 500-event batch meant 500 sequential network round-trips before a single insert.

I fixed it at the interface, not just the adapter. Deduper.Seen now takes the whole batch and returns the already-seen IDs from one MGET. 500 round-trips became one, and throughput went to 40 to 50k events/sec.

Gotcha: CROSSSLOT. Months later, on Redis Cluster, that MGET started failing with CROSSSLOT. In cluster mode keys are spread across hash slots, and a single multi-key command can't span slots. Pipelined single-key GETs fixed it and still cost one network round-trip. If you develop against single-node Redis and deploy to a cluster, run your tests against a cluster too.

The load test ran on one laptop, with the load generator on the same machine:

Rate p95 latency Errors Worker
10k/sec 1.28 ms 0% keeps up
40k/sec 2.89 ms 0% keeps up
60k/sec 3.33 ms 0% small lag, recovers
80k/sec 4.24 ms 0% falls behind

At 60k/sec the worker fell behind, the buffer held the overflow, and all 882,001 events still landed. Our production target was 1 to 2k/sec.

One bad event, whole batch gone

In July, slide engagement numbers started looking suspiciously low. The widget had begun sending a new media_zoom event that the server's allow-list didn't know about, so validation rejected the whole request with a 400.

On the server, that looked correct. The client saw it differently: the SDK batches events and treats any 4xx as "don't retry". So every batch that contained a single zoom event lost all of its events, including impressions, reads and clicks.

The old rule, "any bad event fails the request", assumed someone was watching the response. In production nobody is. Now invalid events are skipped and counted in the 202 response, and the valid ones go through. Only a batch where everything is invalid still gets a 400. At a fire-and-forget boundary, strict validation that throws away good data does more damage than the bad event.

Phase 3: Exact Numbers, Made Fast

One announcement showed 3,795, 3,806, 3,809 and 3,821 users in four panels side by side. ClickHouse's uniq() is a HyperLogLog estimate with 1 to 2% error, and each panel computed its own.

Caching one number would only have hidden the problem. A dashboard that's a second slower beats one that gives four answers, so I switched to uniqExact() and quantileExact() everywhere, then made it fast with materialized views. Every insert into the raw events table also updates small daily rollup tables, so dashboards read kilobytes instead of scanning gigabytes, and the rollups are never stale.

Gotcha: return types. quantile() always returns Float64, but quantileExact() on an integer column returns an integer. The Go scanner expected Float64, so the commit that made percentiles exact broke every percentile chart until each call was wrapped in toFloat64().

Phase 4: What Production Taught Us About Failure

Every call to ClickHouse, Mongo and Redis goes through a circuit breaker: five failures in a row and it fails fast for 30 seconds. Production showed three different ways that goes wrong.

A cache miss tripped it. The library's default counts every error as a failure, including redis.Nil, which just means "key not found". A cold cache produced five misses in a row and the breaker opened, failing the write that saves each event. In a load test only 149 of 60,000 events landed. Treating a miss as a success fixed it.

Cancelled requests tripped it. Users navigating away cancelled a burst of requests, and that opened the Mongo and ClickHouse breakers while both databases were healthy. Counting cancellation as a success would be wrong too, since it resets the failure streak and could stop the breaker from ever opening in a real outage. It needs a third outcome:

IsExcluded: func(err error) bool { return errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) }, 

Every instance retried at once. All instances opened together, then retried the database at the same moment, which set off MongoDB Atlas's own rate limiting. Up to 20% random jitter on the open timeout fixed it.

The last incident wasn't the breaker at all. Over two days I found 161 dropped event batches, each logged as context canceled. The widget sends its last events with a beacon as the page closes, and the beacon disconnects immediately. The handler had tied the Redis write to the request's context, so the write died with the connection. Those were exactly the end-of-session events the analytics depend on most.

publishCtx, cancel := context.WithTimeout( context.WithoutCancel(r.Context()), publishTimeout) 

Once you've replied 202 Accepted, the work you promised shouldn't depend on whether the client is still there.

Phase 5: The Second Feature

A month in, Flabs needed live location tracking for phlebotomists, the staff who collect samples from patients' homes. It had nothing to do with announcements. Building it into the Node monolith would have brought back exactly the firehose I'd kept out of the CRM, and a new microservice would have needed its own copy of auth, database clients, breakers, workers and deployment.

It went in as one more Pulse module instead. GPS pings take the same path as engagement events (stream, worker, ClickHouse) and get circuit breakers, auth and lab scoping for free. The module only had to add what was actually new. A shift has one location stream, and each booking's route is a time slice of it, so overlapping bookings cost nothing extra. The module grew to about 50 commits without any changes to the announcement, survey or analytics code.

What I'd Tell Myself Earlier

  1. Separate accepting work from doing it. A buffer between "accepted" and "stored" made database incidents invisible to users, and doubled as ClickHouse's batching layer.
  2. Read your library's defaults. The breaker's default treated cache misses as outages.
  3. At a fire-and-forget boundary, nobody reads your errors. Accept what you can and count the rest.
  4. Approximate numbers are a product decision. Go exact first, then make it fast.
  5. Test against what you deploy. Single-node Redis hid a cluster-only bug, and fake identities in tests hid an auth bug.
  6. Structure pays off on the second feature. Ports and adapters felt like overhead in week one and paid for themselves in week four.

The full version, with every trade-off, is on the CC Club MNNIT blog. Find me on LinkedIn or GitHub.

原文:https://www.a8q9.cn/en/article/building-pulse-an-event-ingestion-and-analytics-backend-that-survives-production-876c1c.html

相关文章