Building Pulse During My Internship: Designing an Event Ingestion and Analytics Backend That Survives Production

How I designed and shipped Pulse, an in-house engagement and analytics engine at Flabs, and why I picked each piece of the stack over the alternatives.

Ayush Jadaun By Ayush Jadaun • Dec 02, 2026

Introduction

In June 2026 I joined Flabs as a backend intern. Flabs builds a CRM used by diagnostic labs across India, and within my first week I was handed a problem that sounded small: replace the third-party widget we used for product announcements.

It turned into Pulse, a Go service that now serves every announcement, survey, ideas board and roadmap inside the CRM, records every interaction users have with them, and answers analytics queries over that data. A month in, it also became Flabs' live location service, tracking phlebotomists (the staff who collect samples from patients' homes) in real time. That feature plugged into the same foundation without a new service, which ended up being the best argument for how Pulse was built. I designed it, wrote it, load-tested it, deployed it and handled it in production. Over six months it collected more than 600 commits and a fair number of production incidents.

This post is less about what Pulse does and more about the decisions behind it. For almost every piece of the stack there was an obvious alternative, and I want to walk through why I picked one over the other, and where production proved me right or wrong. If you're heading into your first backend internship, this is the post I wish I'd read before mine.

The problem: we couldn't see anything

Flabs used Frill for its changelog, feature-voting board and roadmap. Frill is a solid tool for public changelogs and voting boards. Our problem was that we'd publish an announcement and get back little more than a view count. We couldn't answer:

  • who actually watched it (which labs, which users, which roles)
  • how long they spent on it, or whether they closed it in two seconds
  • which slide of a five-slide carousel lost them
  • whether they clicked the call-to-action, tried the feature, or answered the survey afterwards

We also couldn't target an announcement to "labs on plan X in Maharashtra that use module Y". A third-party widget can't do that because it doesn't know who our labs are. That data lives in our own database.

So the brief became: build our own engagement engine, with targeting tied to our lab data and analytics deep enough to answer those four questions.

Requirements

Before writing code I wrote down what "done" meant. Doing this as an intern also made it much easier to agree on scope with my team.

Functional

  • Serve announcements, banners, popups, surveys, an ideas board and a roadmap to an in-app widget.
  • Target every piece of content with one shared rule engine (lab, role, region, city, plan, cohort, lab size, modules).
  • Record every interaction (impression, slide view, visible dwell time, read completion, CTA click, vote, survey answer) as an immutable event.
  • Give the product team an admin dashboard to slice that data.

Non-functional

  • The tracking call must never slow the CRM down. Fire-and-forget, single-digit milliseconds.
  • No lost events and no double counting. Browsers retry, and beacons sometimes fire twice.
  • Numbers must be exact. If two dashboard panels disagree, nobody trusts either.
  • Strict tenant isolation. A lab must never see another lab's data.
  • Cheap to run.

The architecture

Pulse architecture: the widget sends content reads and tracking events to a hexagonal Go service, which stores content in MongoDB, buffers events in Redis Streams, batch-inserts them into ClickHouse through a worker pool, and serves the admin dashboard from ClickHouse rollups

There are three paths through the service:

  1. Content. The widget asks "what should I see?", Pulse checks the targeting rules and returns matching content from MongoDB.
  2. Write path. The widget sends batches of events to POST /pulse/track. Pulse validates them, appends them to a Redis Stream and replies 202 Accepted. A background worker moves them into ClickHouse.
  3. Read path. The admin dashboard queries analytics, which Pulse answers from ClickHouse, preferring small pre-aggregated tables.

The rest of the post is the decisions that produced this picture.

Decision 1: build it, or buy something better?

The first question wasn't technical. Before building anything, I had to justify not just buying a better tool.

OptionWhat we'd getThe catch
Keep FrillZero effortNo per-user or per-slide data, no targeting on our lab data
A product analytics SaaS (Mixpanel, Amplitude)Great dashboardsAnalytics only, no content or targeting. Per-event pricing grows with usage, and our user data leaves our servers
Self-hosted PostHogOpen source, owns the dataAnother large system to run, and still doesn't do announcements, surveys or targeting
Build PulseContent, targeting and analytics in one place, joined to our dataWe have to build and run it

The deciding factor was that the valuable part, joining engagement to our own lab data, is exactly what an external tool can't do. Once that was clear, building was the cheaper option in the long run.

Decision 2: Go, not another Node service

Flabs' main backend is a Node.js monolith, so the default would have been to add Pulse to it, or write a new Node service.

OptionProsCons
Add to the existing Node monolithNo new deployment, shared codeThe event firehose would compete for the same event loop as every CRM request. A tracking spike could slow down billing
New Node serviceSame language as the teamSingle-threaded event loop for a CPU-heavy ingest path, large node_modules image
New Go serviceGoroutines make a worker pool trivial, one static binary, low memoryA second language in the company

Isolation was the main reason. Ingest traffic is bursty by nature, and I didn't want a burst of tracking events to affect the CRM that labs depend on. Go then made the service itself simple: the worker pool is a handful of goroutines, and the whole thing ships as a single distroless binary in a Docker image of about 15MB.

Decision 3: a modular monolith, not microservices

Pulse has about a dozen domains: announcements, banners, surveys, ideas, roadmap, popups, targeting, tracking, analytics and a few more. It would have been easy to make each one a microservice.

I didn't, because we were one team (for most of the project, one person) and microservices mostly solve problems of many teams. Instead, Pulse is one deployable with hard internal boundaries, in the hexagonal (ports and adapters) style:

  • internal/modules/* holds the domain logic, one folder per domain.
  • internal/platform/* holds the infrastructure: ClickHouse, Mongo, Redis, auth, rate limiting, circuit breakers.
  • Domain code never imports a database driver. The tracking pipeline depends on three interfaces (EventStore, Deduper, SegmentResolver), and the adapters implement them.

The payoff came quickly. Because the pipeline only knows about interfaces, I can test it against in-memory fakes in milliseconds, without Docker or a real database. Every bug fix later in this post came with a test that ran in under a second.

Decision 4: three databases, each with one job

This is the decision I get asked about most. Why three stores instead of one?

StoreJobWhy this one
MongoDBContent and targeting rulesContent has nested, changing shapes (carousels, A/B variants, survey questions). The CRM already uses it, so Pulse can read real lab data for targeting
Redis StreamsIngest buffer, dedup keys, cachesSub-millisecond appends and consumer groups with acknowledgements
ClickHouseAnalyticsColumnar storage for an append-only firehose, and materialized views that pre-aggregate on insert

And the alternatives I turned down:

"Just use MongoDB for everything." Mongo is great for documents, but counting distinct users across hundreds of millions of events with $group is slow and expensive. Analytics wants a columnar store.

"Use Postgres with TimescaleDB." Honestly, this would have worked at our current volume. ClickHouse won on two points: its AggregatingMergeTree engine makes rollup tables almost free, and it compresses event data extremely well, which keeps storage cheap as data grows.

"Put Kafka in front." Kafka is the textbook answer for event ingestion. At our scale it would have been a large system to run for a workload Redis Streams handles fine. Redis Streams gives the same core features I needed (a durable buffer, consumer groups, acknowledgements), and we already ran Redis. If we outgrow it, the buffer is behind an interface, so swapping it touches one adapter.

"Write straight into ClickHouse from the request." This is the one that looks simplest and is the most wrong, which brings us to the write path.

Decision 5: the request never waits for the database

The write path: the handler validates, enriches, appends to a Redis Stream and answers 202 in milliseconds; after that, a worker pool dedups each batch in one round-trip and inserts it into ClickHouse, acknowledging the stream once stored

When the widget sends events, the handler does four quick things: validate, attach the lab's segment (from a cache), append to a Redis Stream, and reply 202 Accepted. The client is done at that point. A worker pool reads from the stream in batches, removes duplicates, inserts into ClickHouse and acknowledges the stream.

Why not insert directly?

  1. Latency and coupling. If ClickHouse is slow or down, a direct insert makes the CRM slow or broken. With a buffer, ClickHouse could be down for ten minutes and users would never notice.
  2. ClickHouse hates small inserts. Every insert creates a "part" on disk, and thousands of tiny inserts lead to Too many parts errors. (Zepto's engineering team wrote a good post about hitting exactly this.) Our worker always inserts hundreds of events at a time, so the buffer doubles as the batching layer.

Duplicates are handled twice: a Redis check on each event ID catches retries, and the ClickHouse table uses ReplacingMergeTree keyed on the ID as a backstop. In load testing I sent the same event ID in every single batch, thousands of times, and ClickHouse ended up with exactly one row for it.

The first bottleneck: 500 round-trips to say "no"

The first version of the worker drained only about 10k events/sec. Profiling showed that the duplicate check made one Redis call per event, so a 500-event batch meant 500 network round-trips before any insert.

I changed the interface so Deduper.Seen takes the whole batch and checks it in one MGET. That one change took drain throughput from about 10k to 40 to 50k events/sec.

Load-test results

All of this ran on one laptop with the load generator (k6) on the same machine, so the top rows partly measure the laptop giving up.

Target ratep95 latencyErrorsWorker keeps up?
10,000/sec1.28ms0%Yes
40,000/sec2.89ms0%Yes
60,000/sec3.33ms0%Small lag, recovers
80,000/sec4.24ms0%No, lag grows

The number I care about more: at 60k/sec the worker fell behind, the buffer held the overflow, and all 882,001 events still landed in ClickHouse. Our production target was 1 to 2k/sec, so a single instance has 20 to 50x headroom.

When one bad event killed a whole batch

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

On the server, that looked correct. But the widget's SDK treats any 4xx as "don't retry", so every batch containing one zoom event lost all of its events, including impressions, reads and clicks.

I changed the rule: invalid events are skipped and counted in the response, and valid ones go through. Only a batch where everything is invalid gets a 400. At a fire-and-forget boundary nobody is reading your error responses, so strict validation that throws away good data does more harm than the bad event.

Decision 6: exact numbers, made fast with rollups

Rollups instead of a cache

Scanning raw events for every dashboard load gets expensive. The usual fix is a cache, but caches go stale and need invalidating. ClickHouse offers something better: materialized views that act as insert triggers. Every batch written to the raw engagement_events table is also aggregated into small daily rollup tables.

CREATE TABLE rollup_entity_action_daily (
    day         Date,
    entity_type LowCardinality(String),
    entity_id   String,
    action      LowCardinality(String),
    events      SimpleAggregateFunction(sum, UInt64),
    users       AggregateFunction(uniq, String)
) ENGINE = AggregatingMergeTree()
PARTITION BY toYYYYMM(day)
ORDER BY (entity_type, entity_id, action, day);

Dashboards read kilobytes instead of gigabytes, and the rollup is never stale because it updates on insert. The query layer picks automatically: if a report only uses columns the rollup has, it reads the rollup, otherwise it falls back to raw events. When one breakdown report was averaging 1.8 seconds, adding a finer-grained rollup fixed it without any caching.

The day four panels disagreed

One announcement showed 3,795, 3,806, 3,809 and 3,821 users in four panels sitting side by side.

Each number was a fair estimate. ClickHouse's uniq() uses HyperLogLog, which is fast but approximate (about 1 to 2% error), and each panel computed its own estimate. Percentiles had the same issue with quantile().

OptionSpeedProblem
Keep uniq() / quantile()FastestPanels disagree, people stop trusting the dashboard
Cache one number and reuse itFastHides the problem, still approximate
uniqExact() / quantileExact()Slower per queryEvery panel agrees to the person

I went exact everywhere. The extra cost is small at our scale, and the heaviest panels read from rollups anyway. For a product team deciding whether an announcement worked, a dashboard that's a second slower beats one that gives four answers.

SQL injection by design, not by luck

Admins can group and filter by any dimension from the dashboard, which is a classic SQL-injection risk. Pulse never puts a user-supplied column name into SQL. Every dimension is looked up in an allow-list map, and anything not in the map is rejected, so a request can only ever reach a column that exists. Values always go in as bound parameters.

Decision 7: circuit breakers, and what counts as a failure

Every call to ClickHouse, Mongo and Redis goes through a circuit breaker. If a database starts failing, the breaker "opens" after five failures in a row and fails fast for 30 seconds instead of piling more load onto it. That's the textbook idea. Production then taught me that the hard part is deciding what counts as a failure.

Pulse's breaker classifier sorts errors into failure (timeouts, refused connections), success (cache misses, no documents) and excluded (cancelled or timed-out callers); before the fix only 149 of 60,000 events landed on a cold cache, after it all 60,000 did, and jittered open timeouts stop every task retrying the database at once

A cache miss is not an outage

While load-testing the email tracking endpoints at 2k events/sec, 99.75% of events disappeared, while the endpoints kept returning success.

The Redis breaker counted every error as a failure, including redis.Nil, which only means "key not found". A cold cache produced five misses in a row, the breaker opened, and for 30 seconds every Redis call failed, including the one that saves the event. Only 149 of 60,000 events landed. After treating a cache miss as a success, all 60,000 did. Mongo's "no documents found" error got the same fix later.

A cancelled request says nothing about the database

On July 17 we had a real incident. A burst of cancelled requests (users navigating away, upstream timeouts) tripped both the Mongo and ClickHouse breakers while both databases were healthy.

The obvious fix is to treat cancellation as a success. That's wrong: a success resets the failure count, so during a real outage, when callers also time out, the breaker might never open. The correct answer is a third category, excluded, which counts as neither.

// Caller-side cancellation says nothing about the dependency's health.
// Treating it as success would reset the streak and could stop the
// breaker from ever opening during a real outage.
IsExcluded: func(err error) bool {
    return errors.Is(err, context.Canceled) ||
           errors.Is(err, context.DeadlineExceeded)
},

Everyone retrying at once

The same incident had a second part. Each server instance has its own breakers, and when they all opened together with the same 30-second timeout, they all retried the database at the same moment. That burst set off MongoDB Atlas's own rate limiting. Adding up to 20% random jitter to each breaker's timeout spread the retries out.

The write that depended on a disconnected client

In October I found 161 batches of events dropped over two days, each logged as context canceled. The widget sends its last events when a page closes, using a beacon that disconnects immediately. Our handler tied the Redis write to the request's context, so when the client disconnected, the write was cancelled too.

Those were exactly the end-of-session events (read completion, where users dropped off) that our analytics depend on most. The fix is one line from Go 1.21:

// Keep request values like the request ID, but drop the cancellation.
publishCtx, cancel := context.WithTimeout(
    context.WithoutCancel(r.Context()), publishTimeout)
defer cancel()

Once you've told a client 202 Accepted, the work you promised shouldn't depend on whether the client is still connected.

Decision 8: treat the widget as untrusted

In August I spent time attacking my own service, trying to break tenant isolation and auth. Two findings stuck with me:

  • Over-sharing in responses. The widget feeds were returning entire internal documents, including targeting rules and internal IDs, to every lab user's browser. Each type now has a ForWidget() method that builds a new struct from an explicit list of allowed fields, so any field added later stays private by default.
  • Tests that skipped the real thing. For one user role, the auth layer resolved identity from the wrong token claim, which widened what that user could see. The unit tests injected identities directly and never parsed a real token, so they missed it. Now every role has a test that starts from a real JWT.

Non-admin analytics requests are also forced to the caller's own lab in a single helper, so no individual report can forget to apply it.

Decision 9: make new features plug into the same spine

The real test of the architecture came in July, when Flabs needed something that had nothing to do with announcements: live location tracking for phlebotomists. Ops wanted to see where every on-duty phlebotomist was, and patients wanted a delivery-app style "your phlebotomist is 10 minutes away" view for their booking.

OptionProsCons
Build it inside the Node monolithBooking data is right thereGPS pings every 30 seconds from every phone is exactly the kind of firehose I kept out of the CRM in Decision 2
A brand-new location microserviceClean separationA second copy of auth, Redis and ClickHouse clients, circuit breakers, workers, migrations, deployment and monitoring
A new module inside PulseReuses all of that on day onePulse's scope grows beyond "engagement"

I added it as a module, and this is where the hexagonal layout paid off. A Pulse module is a folder in internal/modules/ with its own domain types, its own interfaces, and adapters that sit on the shared platform clients. Adding one means writing that folder and wiring it up in main.go. Everything else already exists:

Already in the platformHow location used it
Redis Streams + worker patternGPS pings follow the same accept-fast path as engagement events: append to a stream, return, and a worker batches them into a ClickHouse location_pings table
ClickHouse with embedded migrationsHistorical ride paths are plain time-range queries
Circuit breakers and retriesEvery new Redis, Mongo and ClickHouse call was protected from the first commit, including all the lessons from Decision 7
JWT auth, lab scoping, rate limitingThe admin map reused the existing admin auth and per-lab scoping

The module only had to bring what was actually new about location:

  • One stream per duty, rides are time slices. A phlebotomist can have several overlapping bookings ("rides") during one shift ("duty"), but they're only ever in one place. So there's a single location stream per duty, and a ride's path is just the slice of that stream between the ride's start and end times. Overlapping rides cost nothing extra: no per-ride writes, and the app never has to report which ride it's on.
  • Redis GEO and sorted sets for the live view, with ClickHouse for history. The same endpoint reads from Redis while a ride is live and from ClickHouse once it's finished.
  • Scoped, signed tokens. The phone gets a token that can only write pings for its own duty, and a patient gets one that can only read their own booking.

Location also brought its own production lessons. Its Redis Lua scripts touch several keys at once, which hit the same CROSSSLOT error on Redis Cluster, so all location keys share a hash tag that puts them on one slot. And phones have unreliable clocks, so a ping's stored time comes from the server's clock. The phone's timestamp is only used to order and slice pings, never stored as the truth.

The location module grew to about 50 commits. Building the feature never required changing the announcements, surveys or analytics code; the only commits that touched both were service-wide passes like better error logging and a performance sweep. That's what I'd point to if someone asked whether the up-front structure was worth it.

What I would tell myself before June

If I could send a note back to myself before the first commit, it would say this:

  1. Write the requirements before the code. Writing "no double counting" and "exact numbers" down on day one decided half of my later technical choices for me, and made it easy to explain those choices to my team.
  2. For every choice, name the alternative you rejected and why. "We used ClickHouse" means little. "We used ClickHouse over Postgres because of rollups and compression, and Postgres would have been fine at our scale" shows you actually thought about it.
  3. Separate accepting work from doing it. A buffer between "accepted" and "stored" turned every database incident into something users never saw.
  4. Defaults are written for the average case, not yours. The circuit breaker library's default treated cache misses as outages. Read what your libraries do by default.
  5. Structure pays off on the second feature, not the first. Ports and adapters felt like overhead in week one. In week four, a completely different product (live location) dropped in as a module without touching the existing code.
  6. Test against what you deploy. Single-node Redis hid the cluster bug, and fake identities hid an auth bug. Realistic tests are cheaper than incidents.
  7. Production is the real teacher. Almost every interesting section of this post is a bug. Being honest about them, and fixing them at the root, taught me more than getting things right the first time would have.

Conclusion

Pulse started as "replace a widget" and became a platform that ingests tens of thousands of events per second, answers exact analytics questions, tracks field staff live on a map, and keeps working when its databases don't. The architecture fits on one diagram, but every box on it is there because of a trade-off, and many of those trade-offs were tested by production within weeks.

If you're interning soon: ask for ownership of something real, write down why you chose each piece, and pay close attention when it breaks. That's where most of the learning is.

Questions or feedback? Find me on LinkedIn or GitHub.