Your cart is currently empty!
Kafka topics for collected events: a design walkthrough
The single topic called scraped
The first Kafka design for a collector almost always looks the same. One topic, named something like scraped or raw-data, with a JSON blob per message containing whatever the scraper produced: sometimes a parsed record, sometimes a page’s HTML, sometimes an error, told apart by a type field someone added in week two. No key, because nobody was sure what to key on. Default partition count. Default retention.
It works for a while. Then a second consumer wants only the parsed records and has to read and discard every HTML blob. A product page grows past the broker’s message size limit and the producer starts throwing errors. The analytics team asks for the latest price per product and someone discovers there’s no way to get it without replaying the whole topic. A parser fix needs a reprocess of last month’s pages, and last month’s pages expired a week ago under the default retention. Records for the same product arrive out of order because they landed on different partitions.
Every one of those is a topic design problem, cheap to avoid at the start and expensive to fix once several consumers depend on the shape.
This piece walks through a topic model for a collector that emits page and record events: which topics to create, what goes in each message, how to choose keys and partition counts, retention and compaction per topic, schema evolution, and the producer and consumer settings that decide whether the design actually holds. The batch-versus-streaming guide in this series covers whether you should stream at all. This assumes you’ve decided to, and that Kafka is the broker. Near the end there’s an honest section on when it shouldn’t be.
We run streaming collection for some jobs and batch for others, and what follows is the layout we’d build today. It’s grounded in Kafka’s documented behaviour. None of it depends on throughput figures, which vary too much between collectors to be worth quoting.
What a collector actually emits
Before naming topics, list the events. A collector does a small number of distinct things, and each produces a different kind of fact.
A fetch happened. The collector requested a URL and got a response, or didn’t. The facts are the URL and the fetch time, the job and proxy pool that ran it, the status and response size, a content hash, and where the raw bytes were stored. This is an operational event. Monitoring and cost accounting care about it. Most business consumers don’t.
A record was extracted. A parser turned a fetched page into one or more structured records: a product with a price, a listing with an address, a job posting with a salary range. The facts are the fields, the parser version, and a pointer back to the fetch that produced them. This is the event most downstream consumers actually want.
A record failed. A page was fetched but parsing or validation failed. The facts are the error, the parser version, and a pointer to the raw page so it can be retried after a fix. The dead-letter guide in this series covers what to do with these; here it’s enough that they’re a distinct event with distinct consumers.
An entity changed. Across many extractions of the same product, what matters to many consumers is only the current state and when it changed. That’s derived from the extraction events rather than emitted by the scraper directly.
A fetch was blocked or throttled. Rate limits, challenges and error pages are fetch outcomes, and they belong in the fetch events with a status. They’re worth calling out because they drive the collector’s own control loop, slowing down a target or pausing a job, and that consumer needs them fast.
Four or five event types, each with its own consumers, its own volume, and its own useful lifetime. That’s the argument for separate topics.
One topic per event type, named consistently
Put each event type in its own topic. It sounds obvious, and mixed topics are still the most common design mistake, because a single topic feels simpler on day one.
Separate topics let each consumer subscribe to exactly the events it needs, without reading and discarding the rest. They let each topic have its own retention, partition count and compaction settings, which matter a lot, as the next sections show. And they give each event type its own schema, instead of one schema with a type field and a pile of optional fields that apply to some types and not others.
A naming convention pays for itself quickly once there are more than a handful. A pattern like <area>.<entity>.<event>.v<major> works well: collect.page.fetched.v1, collect.record.extracted.v1, collect.record.failed.v1, collect.entity.latest.v1. The area groups a team’s topics for access control. The entity and event say what’s inside. The version suffix leaves room for a breaking schema change later, which gets a new topic rather than a mutation of the existing one.
Resist per-target topics, such as one topic per site you collect. They look tidy with three targets and become unmanageable with three hundred, since each topic carries partitions and metadata, and consumers that want all targets end up subscribing by pattern and breaking when names drift. Put the target in the message and, if you need per-target access control, in a header. The exception is a hard isolation requirement, such as a client whose data contractually can’t share a topic with anyone else’s, where separate topics with their own ACLs are the cleanest guarantee.
If you’re running collection for several clients, decide early whether client is a topic dimension or a field. Changing that later means migrating every consumer.
Keep raw HTML out of the log
The fetch event is the one people are tempted to fill with the page itself. Don’t.
Kafka is built for many small messages, and its defaults reflect that. The broker’s default maximum message size is roughly one megabyte, and the producer’s default maximum request size matches it. Some modern product pages exceed that as uncompressed HTML, so a design that puts pages in messages fails on exactly the heavy pages you most need, with a producer error in the collector. You can raise the limits on broker, topic, producer and consumer together, and people do, but large messages put pressure on broker memory, replication and consumer fetch sizes, and they turn every consumer of that topic into a consumer of bulk bytes.
The pattern that holds up is sometimes called a claim check. The collector writes the raw response to object storage, keyed by something stable like the content hash or a fetch ID, and the fetch event carries a pointer to it: the bucket and key, plus the object’s size and hash. Consumers that need the HTML, typically parsers, fetch it from storage. Everything else reads a message of a few hundred bytes.
This also lines up with how raw captures should be kept anyway. The storage-format and retention guides in this series argue for keeping raw pages in cheap object storage, compressed, under lifecycle rules. The fetch topic then becomes an index into that store, with a short retention, while the bytes live as long as your retention policy says.
The same logic applies, less strongly, to extracted records. A record with a long free-text description or an array of image URLs is fine in a message. A record with an embedded document or a base64 image isn’t. Keep messages to structured fields and pointers.
One practical detail: write to storage before producing the event, and make the storage key deterministic. If the producer retries, the event points at the same object, and if the write succeeded but the produce failed, a retry doesn’t create an orphan.
The event envelope
Every message on every topic should share an envelope of common fields, with the event-specific payload inside it. Consumers can then handle routing, deduplication and tracing the same way on every topic.
A workable envelope has an event_id, unique per event, used for deduplication. It has a schema_version for the payload. It has an occurred_at timestamp for when the thing happened, such as when the page was fetched, which is distinct from when the message was produced and from Kafka’s own record timestamp. It has the source, meaning the target site or feed, a job_id and run_id so events can be traced back to a crawl, and a producer field naming the service and version that emitted it.
Record events add a parser_version, which is what makes reprocessing and debugging possible later. When a field looks wrong six weeks from now, the first question is which parser produced it, and the answer should be on the message. They also carry a fetch_id pointing back to the fetch event, which carries the pointer to the raw page. That chain, record to fetch to raw bytes, is what lets you prove where any value came from.
Kafka also supports record headers, key-value pairs outside the payload. They’re useful for metadata consumers want to filter on without deserialising the payload, like the source or the schema version. Keep the authoritative copy in the payload, because not every tool in a pipeline preserves headers faithfully, and a sink that writes messages to a warehouse may drop them.
Timestamps deserve care. Put them in UTC, with an explicit format, and be clear about which one is which. The dedup guide in this series makes the point that two sources rarely agree on clocks. An envelope that separates “when it happened on the site” from “when we fetched it” from “when we emitted it” saves a lot of confused debugging.
Choosing keys
The message key decides which partition a message lands on, and in Kafka ordering is guaranteed only within a partition. So the key is really a statement about which events must stay in order relative to each other.
With the default partitioner, messages with the same key go to the same partition, as long as the partition count doesn’t change. Messages with no key are spread across partitions with no ordering relationship at all.
For record events, key by entity. That’s a stable, canonical identifier for the thing the record describes, such as the source plus the product ID, or a normalised listing URL. The dedup guide covers building that canonical key, and the same key belongs here. Keying by entity means every extraction of one product lands on one partition in order, so a consumer maintaining current state sees updates in the order they were produced. It also spreads load well, because a collector usually touches many entities.
For fetch events, key by canonical URL. Ordering per URL is useful for change detection, and URLs spread evenly.
For the entity-state topic, the key must be the entity key, because compaction, covered below, keeps the latest message per key.
The key people reach for first, and should usually avoid, is the target site. It feels natural, since so much logic is per site, but it creates a partition per big site in practice. One large target produces a large share of the traffic, all of it lands on one partition, and that partition’s consumer falls behind while others sit idle. If you need per-site ordering for something like rate control, that consumer can read the fetch topic and group by site in memory, without the whole topic paying for it.
Never key by something that changes for the same entity, such as a timestamp or a proxy session. That breaks per-entity ordering and makes compaction useless.
Hot keys and skew
Even with a good key, some entities are much busier than others. A flagship product re-checked every few minutes, a search results page crawled on every run, a listing that changes constantly. Each busy key lands on one partition and makes it busier than the rest.
With entity keys, this is usually mild, because a collector’s traffic is spread across many entities and a few busy ones don’t dominate. It becomes a real problem when the key space is small, such as keying by site with a few dozen sites, or when one entity is responsible for an outsized share of events.
The symptom is consumer lag concentrated on one or two partitions while the others stay near zero. Kafka’s consumer-group tooling reports lag per partition, and that’s the view to check before concluding the whole topic is under-provisioned.
The fixes, in order of preference. First, choose a finer key, since site plus entity instead of site almost always solves it. Second, reduce the hot key’s volume at the source: if a page is fetched every few minutes but changes daily, the incremental-scraping and recheck-frequency guides are the better fix. Third, if a key genuinely needs very high volume and doesn’t need strict ordering, add a small salt to its key, like a suffix from zero to three, so its messages spread across a few partitions. That gives up per-key ordering for that key, so consumers have to tolerate reordering for it, which usually means using an explicit version or timestamp in the payload and ignoring older updates.
Custom partitioners exist and can route specific keys deliberately. They’re rarely worth the complexity for collection workloads. Getting the key right does the same job with less to maintain.
Partition counts
Partitions are Kafka’s unit of parallelism. Within a consumer group, each partition is read by exactly one consumer at a time, so the partition count is the maximum number of consumers in a group that can do useful work. Ten partitions and twenty consumers means ten of them sit idle.
That makes partition count a forecast. Start from how many consumer instances the slowest consumer of the topic might need at peak. For a parser consuming fetch events, that’s the number of parser workers you might run during a big recrawl. For a warehouse sink consuming records, it might be far fewer. The topic needs at least the larger number.
Two properties make it worth erring on the side of more. You can increase a topic’s partition count, but you can’t decrease it without recreating the topic. And when you increase it, the default partitioner’s mapping from key to partition changes for many keys, so new messages for an existing key can land on a different partition than its older messages. For a short period, consumers can see that key’s events out of order across the two partitions. For topics where per-key order matters, that’s a real disruption, and on a compacted topic it can leave the old partition holding a stale value for a key whose new value lives elsewhere.
Erring towards more isn’t free either. Each partition carries broker overhead, file handles and replication traffic, and very high counts slow down leader elections and recovery. For a collector’s topics, a moderate count chosen with headroom beats both the default and an extravagant number. A count with many divisors makes it easy to run evenly balanced consumer groups of several sizes.
Different topics can and should have different counts. The fetch topic, read by a scaled-out parser pool, may need more. The failure topic, read by one retry service, needs few.
Write the reasoning down next to the topic definition. The next person who wants to double the count needs to know which consumers depend on per-key order.
Retention per topic
Retention is how long Kafka keeps messages before deleting them, set per topic by time, by size, or both. The broker default is usually seven days. The right value differs a lot between a collector’s topics, because each one answers a different question about how far back anyone needs to go.
Fetch events can be short-lived. They’re an index into raw storage and an operational feed. A few days is typically enough for the parser to catch up after an outage and for monitoring to look back over recent runs. The raw bytes they point to live in object storage under their own lifecycle rules, so expiring the event doesn’t lose the page. If you keep a longer history of fetches for cost accounting, sink them to the warehouse and query them there.
Record events need longer retention, sized to your replay horizon. The main reason to keep records in Kafka is to let a consumer reprocess them, for example a new consumer bootstrapping or an existing consumer replaying after a bug fix. Ask how far back a replay realistically needs to go, then add margin. If the answer is months, it’s usually cheaper to replay from the warehouse or from raw storage via a reparse, as the reparsing guide describes, than to keep months of records on broker disks.
Failure events should live long enough for someone to fix the parser and retry them. That depends on how quickly your team responds to parse failures. If a fix typically lands within a week, keep them for several weeks. Dropping failures before they can be retried turns a parser bug into permanent data loss.
Size-based retention is a useful safety net alongside time-based retention on topics whose volume can spike, like fetch events during an unusually large crawl. It stops a surge from filling broker disks. Just remember that size-based retention can delete messages earlier than the time setting suggests, so replay guarantees are only as good as the smaller of the two.
Recent Kafka versions also support tiered storage, which moves older segments to object storage while keeping them readable. Where your platform offers it, check it before settling on a short window.
Compacted topics for latest state
Many consumers of collected data don’t want history. They want the current state: the latest price for each product, the current status of each listing. Rebuilding that from a stream of extraction events means replaying everything and keeping the last value per key, which is exactly what Kafka’s log compaction does for you.
A compacted topic has its cleanup policy set to compact instead of, or as well as, delete. Kafka then guarantees that it retains at least the most recent message for each key, and eventually removes older messages for the same key. A consumer that reads the topic from the beginning ends up with the latest value for every key, without needing the full history.
For a collector, that’s the collect.entity.latest.v1 topic. A small service consumes record events, compares each record against the current state for its key, and produces to the compacted topic only when the entity actually changed, using the content hash to tell. Consumers that want current state read this topic. Consumers that want history read the record topic or the warehouse.
Deletions are represented by tombstones: a message with the entity’s key and a null value. When a product disappears from a site and your logic decides it’s gone rather than temporarily missing, produce a tombstone. Compaction eventually removes the tombstone itself too, after a configurable delay, so consumers need to read regularly enough not to miss it, or they’ll never learn the entity was deleted.
The combination of compact and delete is useful when you want latest-state semantics but don’t want entities that haven’t changed in a very long time to live forever. With both policies, old segments are removed by time even if they hold the latest value for a key.
Compaction only works if the key is stable and the value is the full current state, never a partial update. A compacted topic of field-level diffs loses information the moment compaction removes earlier diffs. Put the full record on each message.
Schemas and how they evolve
Every topic needs a schema, and every schema will change. Plan for the change on day one.
The common setup is a schema registry holding versioned schemas in Avro, Protobuf or JSON Schema, with producers registering schemas and consumers fetching them to deserialise. Registries enforce compatibility rules on each new version, so a producer can’t publish a change that breaks existing consumers. Backward compatibility, where new consumers can read old data, is the usual default for event topics. Adding an optional field with a default passes. Renaming or removing a required field fails.
If a registry is more infrastructure than you want, versioned JSON with a schema_version field in the envelope and a written schema in the repo is a workable minimum. It lacks enforcement, so pair it with contract tests in CI that validate sample messages from producers against the schema consumers expect.
Scraped data has a particular evolution pattern. Target sites add fields, remove fields and change formats, and the collector’s output changes in response. The schema-drift and versioning guides cover detecting those changes at the source. On the topic side, the rule is that a site change should become a planned, compatible schema change, not a surprise. New fields arrive as optional. A field the site stopped providing becomes nullable before it disappears. A genuinely breaking change, such as a price moving from a string to a structured amount and currency, goes to a new major-version topic, with both topics produced in parallel until consumers migrate.
The data-contracts guide in this series covers the agreement with consumers that sits on top of this. The schema is the machine-checkable part of that contract, so treat changes to it with the same care as changes to an API.
Producer and consumer settings that matter
A few settings decide whether the topic design actually delivers what it promises.
On the producer, acks=all makes the broker confirm a write only after all in-sync replicas have it, and combined with a replication factor of three and min.insync.replicas of two it’s the standard setting for data you don’t want to lose. Idempotence, enabled by default in recent Kafka clients, prevents duplicates from producer retries and preserves per-partition ordering across those retries. Compression is set per producer, with zstd, lz4, snappy and gzip all supported, and structured JSON records compress well, so turn it on.
On the consumer side, the thing to design around is that delivery is at-least-once in practice. A consumer that processes a message and then crashes before committing its offset will process it again after restart. Kafka offers transactions and exactly-once semantics for Kafka-to-Kafka processing, but the moment a consumer writes to a database or an external API, duplicates are possible and the consumer has to be idempotent. The event_id in the envelope is what makes that easy: upsert by entity key and skip events already applied, or keep a short-lived record of processed event IDs.
Commit offsets after processing, not before. Committing first and crashing loses the message silently.
Replay is a consumer-group operation. Kafka’s tooling can reset a group’s offsets to a timestamp or to the earliest retained message, so after fixing a consumer bug you stop the group, reset it to before the bug, and let it reprocess. That only works within retention, which is why record-topic retention should match your replay horizon, and it only works safely if the consumer is idempotent.
Monitor consumer lag per partition for every group. Rising lag on one partition means skew. Rising lag everywhere means the consumer can’t keep up.
When Kafka is more than the job needs
Everything above assumes Kafka earns its operational cost. For many collectors, it doesn’t.
Kafka pays off when several independent consumers need the same events, when replay is a real requirement, when volume is high and sustained, or when a platform team already runs it. A collector feeding one warehouse, on a schedule, at moderate volume, gets little from it and pays for brokers, controller quorum, upgrades, monitoring and the expertise to run them. Managed services and Kafka-compatible alternatives remove some of that, not all.
The simpler options cover a lot of ground. A Postgres table used as an outbox or a queue, with records written in the same transaction as their state, handles moderate volume with one consumer and gives you SQL for free. Object storage with files per batch, picked up by the warehouse loader, is the batch design most collectors should start with, as the batch-versus-streaming guide argues. Redis Streams and managed queues each fit particular shapes, and a separate guide in this series compares them for the related problem of holding a crawl frontier, which is a different job from carrying collected events.
A useful test: if you can’t name at least two consumers that will read the same topic independently, or a concrete replay you’ll need to run, start without Kafka. Keep the event design anyway. The envelope, the entity keys, the separation of fetch, record and failure events, and the claim-check pointers all work on a queue table or in files, and they make a later move to Kafka a transport change rather than a redesign.
That’s the real point of this walkthrough. The topic model is mostly an event model, and the event model is worth getting right whichever transport carries it.
A worked layout to start from
Here’s the layout we’d start with for a collector emitting page and record events, with the reasoning compressed.
collect.page.fetched.v1: keyed by canonical URL, a partition count sized to the peak parser pool with headroom, delete policy with a short retention of a few days plus a size cap. Payload is fetch metadata and a pointer to the raw object in storage. Consumers are parsers, cost accounting and the collector’s own rate-control loop.
collect.record.extracted.v1: keyed by entity, a partition count sized to the largest consumer group, delete policy with retention matching your realistic replay horizon. Payload is the full structured record with parser version and fetch ID. Consumers are the warehouse sink, the state builder and any team that needs history.
collect.record.failed.v1: keyed by canonical URL, few partitions, delete policy with retention of several weeks. Payload is the error, parser version and raw pointer. Consumers are the retry service and alerting.
collect.entity.latest.v1: keyed by entity with the same partition count as the record topic, compact policy, produced only on change, with tombstones for confirmed deletions. Consumers are anyone who wants current state.
Every message carries the envelope. Every schema is registered with backward compatibility. Producers use acks=all and idempotence. Consumers are idempotent by event ID and commit after processing. Lag is monitored per partition.
That’s four topics, each with a clear job. It’s enough to serve most collectors that genuinely need Kafka, and small enough to understand in one sitting.
For the rest of the pipeline around a design like this, from storage formats to validation to the contracts with the people downstream, the full set of guides is at Data Research Tools.
Get new guides and videos first — join the Telegram channel.
Leave a Reply