Skip to content

Part 9 · Blueprint 58

Ad Click Aggregation & Real-Time Bidding (RTB)

14 min reading · Sources · Editorial review pending

A fast dashboard and a corrected billing total have different finality rules.

More
20px
Reading list
Page details

Published date · Last edited:

Draft edition. Editorial review and supplementary reading recommendations are still being completed.

Format: Architecture walkthrough. Prerequisites: the beginner bootcamp. Chapter prerequisites: Idempotency Keys & Distributed Retries, Time, Clocks & Distributed Ordering: Lamport to TrueTime, Real-Time Stream Processing Engine (Apache Flink Internals).

Sixty-second mental model

Problem: A fast dashboard and a corrected billing total have different finality rules.

Use: Specify attribution windows and separate provisional from reconciled totals.

Design boundary: Count and attribute advertising events under duplicates and late arrival; keep low-latency bidding separate from analytical correction. A click identity and its attributed impression are distinct facts.

Layer 1 · Intuition

Hypothetical scenario: Northwind is designing ad event aggregation. Maya represents product requirements, Dev implementation and Priya reliability. The team must agree what one ad event means and which component owns the deduplicated event ledger.

Think of a ledger matching views and clicks before billing. Separate the requester from deduplicated event ledger, then identify the retained evidence needed after failure.

Authority
The entitled state owner.
Invariant
A rule preserved across concurrency and failures.

Architecture and worked reasoning

Design boundary: Count and attribute advertising events under duplicates and late arrival; keep low-latency bidding separate from analytical correction. A click identity and its attributed impression are distinct facts.

Responsibilities on the request path

Ad event aggregation: responsibilities and request directionCount and attribute advertising events under duplicates and late arrival; keep low-latency bidding separate from analytical correction. A click identity and its attributed impression are distinct facts.Event ingressIdentity filterEvent-time windowsCorrection ledger
Count and attribute advertising events under duplicates and late arrival; keep low-latency bidding separate from analytical correction. A click identity and its attributed impression are distinct facts.

Workload and limiting resource

Hypothetical 1,000,000 delivered click events include 20,000 repeated identities, leaving 980,000 unique identities under the selected deduplication rule. A 2% change in billing cannot be inferred unless those repeats otherwise met the billing contract. At 10,000 identities/s and 600-second horizon, raw retained identity count is 6,000,000.

Keep the units attached to each intermediate result. The assumptions above describe a hypothetical exercise, not observed vendor capacity. A real capacity decision also needs a measured service curve, skew, recovery traffic and an explicit admission policy for overload.

Mutation or publication path

Ad event aggregation: mutation boundaryValidate identity/time and tenant/campaign scope. Then: Deduplicate within a declared horizon. Then: Publish provisional counts and correction events under explicit finalization rules.Step 1
Validate identity/time and tenant/campaign scope.
Step 2
Deduplicate within a declared horizon.
Step 3
Publish provisional counts and correction events under explicit finalization rules.
Validate identity/time and tenant/campaign scope. Then: Deduplicate within a declared horizon. Then: Publish provisional counts and correction events under explicit finalization rules.
  1. Validate identity/time and tenant/campaign scope.
  2. Deduplicate within a declared horizon.
  3. Publish provisional counts and correction events under explicit finalization rules.

Observation and recovery path

Ad event aggregation: observation boundaryRead aggregates with window/version metadata. Then: Separate accepted clicks from attributed billable outcomes. Then: Apply late corrections without erasing audit history.Step 1
Read aggregates with window/version metadata.
Step 2
Separate accepted clicks from attributed billable outcomes.
Step 3
Apply late corrections without erasing audit history.
Read aggregates with window/version metadata. Then: Separate accepted clicks from attributed billable outcomes. Then: Apply late corrections without erasing audit history.
  1. Read aggregates with window/version metadata.
  2. Separate accepted clicks from attributed billable outcomes.
  3. Apply late corrections without erasing audit history.

Failure that changes the decision

Hypothetical scenario: An event arrives after the billing window closed. Record a defined correction or review outcome rather than silently rewriting a finalized invoice.

Attempt this decision before reading the explanation

Does processing-time order establish the correct attribution window?

No. Network delay and retries reorder arrival. Use the declared event-time and attribution policy, including late and untrusted timestamps.

Supporting mechanism analysis

Hypothetical scenario: Northwind. Maya represents product, Dev implementation and Priya reliability. The following workflow develops the underlying mechanism.

Hypothetical scenario. Search and activity-view workers share Northwind’s queue. All items are consumed, but each view misses changes that the other worker received. Dev has balanced consumption while accidentally dividing two different responsibilities.

Choose the consumption contract before selecting a product. Distinguish competing work from independent readers and retained history. Carry the repeated-effect protection from page 20 into each responsibility; changing the transport does not remove it.

Before you continue: Should independent projections compete for a single copy of each change?

That shares deliveries rather than establishing that every independent projection receives every needed change. It can fit interchangeable workers, not the stated requirement.

This makes fan-out and replay explicit. The next calculation counts the resulting work and retention rather than assuming that one consumed record completes every projection.

A competing-work queue distributes tasks among consumers that perform the same logical responsibility. Adding workers normally shares that responsibility; it does not mean every worker performs every task. If all search workers update the same protected projection, that distribution can be appropriate.

Publish-subscribe describes distribution to independent subscriptions. Search and an activity projection can each need the same change, with separate progress and failures. Their subscription positions or queues are not interchangeable with the count of worker processes inside one responsibility.

A retained event stream stores a sequence of records under a retention policy and allows consumers to track progress through it. Several independent consumers can read the same retained history. That supports replay and rebuilding where the history and transformation contract are sufficient. Retention is a declared limit, not a promise to remember everything forever.

A command asks for an action, such as preparing a specific uploaded image. An event records that something happened, such as a product version becoming authoritative. A query asks for information. Transporting all three as messages does not give them identical business meaning.

Replaying a product fact to rebuild a search view differs from replaying a command that sends a customer message. The latter can repeat an external effect unless its contract protects it. A retained transport makes replay possible; the application determines whether a particular replay is meaningful and safe.

Hypothetical scenario. Choose a Kafka topic partition containing offsets 40, 41 and 42. Each record has a product key, source revision and schema identity. Search and activity projections use different consumer groups, so each group maintains its own progress rather than dividing the two responsibilities between competing workers.

A partition is an ordered sequence within its selected scope, not a global order across the topic. Key choice can keep one product's changes together while making a popular key a bottleneck. Broker replication, retained log bytes and group offsets solve different responsibilities. Committing an offset records progress under the consumer's policy; it is not evidence that an unrelated remote effect committed.

Primary mechanism reference: Kafka design and transaction scope . Use its implementation scope when evaluating this design.

Hypothetical scenario. Open one Kafka partition as a sequence of segment files. Suppose a closed segment contains offsets 40–49 and the active segment currently contains 50–54. The append path extends the active segment; a fetch uses an offset to locate retained records. These selected boundaries illustrate file organization, not Kafka’s configured segment sizes.

Suppose the selected delete-retention policy makes the first segment eligible and it is removed. The earliest retained offset is now 50. Search’s next position 47 is three offset positions behind that boundary: 50 − 47 = 3, namely 47, 48 and 49 in this contiguous example. Its committed position cannot recover those bytes. Activity can still resume at 52. Search must declare a gap and use a complete rebuild path; silently resetting to 50 changes its coverage.

Kafka’s design documentation separates replication, consumer progress and retention, and describes compaction as a different cleanup policy. Compaction can remove superseded keyed records while preserving surviving offsets. Therefore offset distance is not generally a count of available records, and a compacted topic is not automatically a complete audit history. State whether a projection needs every transition or only sufficient current-state evidence before selecting cleanup.

Hypothetical worked example. Preserve the selected two product changes per second. If three independent projections each require every change, logical subscription deliveries are 2 × 3 = 6 per second before retries. A single competing queue carrying two tasks per second does not become six complete projection obligations merely because three different teams attach consumers.

For a retained-history estimate, choose five hundred payload bytes per change. One day contains 24 × 60 × 60 = 86,400 seconds, so raw daily payload is 2 × 500 × 86,400 = 86,400,000 bytes. Seven days retain 7 × 86,400,000 = 604,800,000 payload bytes under the uniform-rate model.

Three copies of that selected retained payload occupy 3 × 604,800,000 = 1,814,400,000 bytes before keys, indexes, batch framing, logs and free space. Consumer delivery traffic and retained broker storage are different quantities. Three subscribers do not necessarily require three separately stored copies of every event inside the broker’s selected storage model.

Retention creates a recovery deadline. If a consumer falls behind beyond the available history, moving its cursor does not reconstruct missing records. A source snapshot plus a compatible change position, or another explicitly complete rebuild path, may be needed.

A stream may define order within a partition while independent partitions proceed separately. Choosing product identity for partitioning can keep one product’s related records together under the selected producer and consumer protocol. It does not automatically establish one global order across the catalogue.

For a conventional partition-assigned consumer group, choose three partitions and five available consumer instances. At most three instances can own a partition simultaneously in that selected model; two have no partition assignment. Adding instances does not divide one assigned partition’s serial processing into arbitrary parallel work.

That is a consequence of the declared assignment model, not a universal claim about every modern queue or Kafka feature. Some systems offer other consumption contracts. Compare the actual selected feature rather than treating the product name as one immutable messaging abstraction.

Layer 3 · Internals

An ad pipeline distinguishes impression identity, click identity and the attribution relation connecting them. Event-time windows can produce provisional aggregates while late arrivals or fraud checks later change the accepted billing population. A watermark does not establish that no earlier click can ever arrive, so both the correction horizon and post-horizon handling must be visible.

Deduplicate by the relevant event identity before incrementing a billable count. Joining streams also requires a retention budget: keeping a hypothetical hour of impression context for 2,000 impressions per second means 2,000 × 3,600 = 7,200,000 impression records before replication and indexing. Campaign spending is a separate invariant from aggregate reporting. Distribute bounded quota reservations to auction workers if a shared balance cannot be checked synchronously for every opportunity. Account for reservations in flight and delayed settlement; a near-real-time chart cannot retroactively prevent overspend already committed at the edge.

Trade-offs and limits

ApproachProvidesRequires
One deduplicated billing ledgerPreserves an auditable event population.Correction and late-arrival work remains visible instead of disappearing.
Streaming provisional countersProvides low-latency reporting.Dashboard freshness is weaker than billing finality or prepaid enforcement.

Recovery decision

Hypothetical scenario: An event arrives after the billing window closed. Record a defined correction or review outcome rather than silently rewriting a finalized invoice.

No. Network delay and retries reorder arrival. Use the declared event-time and attribution policy, including late and untrusted timestamps.

Write your design before revealing the review

Does processing-time order establish the correct attribution window?

Evidence you can explain in your own design

Drafts and self-review are stored only in this browser. They are separate from reading completion.

Compare your decision

No. Network delay and retries reorder arrival. Use the declared event-time and attribution policy, including late and untrusted timestamps.

An event arrives after the billing window closed. Record a defined correction or review outcome rather than silently rewriting a finalized invoice.

Check your understanding

Does processing-time order establish the correct attribution window?

No. Network delay and retries reorder arrival. Use the declared event-time and attribution policy, including late and untrusted timestamps.

How would you recover from this failure: An event arrives after the billing window closed. Record a defined correction or review outcome rather than silently rewriting a finalized invoice.

Start with the exact boundary that failed. Validate identity/time and tenant/campaign scope. Deduplicate within a declared horizon. Publish provisional counts and correction events under explicit finalization rules. Then recover evidence through the observation path: Read aggregates with window/version metadata. Separate accepted clicks from attributed billable outcomes. Apply late corrections without erasing audit history. Preserve the distinction between a confirmed state change and an unavailable response.

Which assumption in the worked calculation would a burst or concentrated tenant invalidate first?

Hypothetical 1,000,000 delivered click events include 20,000 repeated identities, leaving 980,000 unique identities under the selected deduplication rule. A 2% change in billing cannot be inferred unless those repeats otherwise met the billing contract. At 10,000 identities/s and 600-second horizon, raw retained identity count is 6,000,000. Recompute the affected resource rather than multiplying unrelated storage and network budgets by the same factor. Count and attribute advertising events under duplicates and late arrival; keep low-latency bidding separate from analytical correction. A click identity and its attributed impression are distinct facts.

Which component in this topology could be removed from a smaller first deployment?

Event ingress, Identity filter, Event-time windows, Correction ledger name responsibilities, not a requirement for separate processes. Co-locate responsibilities when their transaction, trust and capacity boundaries permit it. Validate identity/time and tenant/campaign scope.

What evidence must a caller have before relying on the observation path?

Read aggregates with window/version metadata. Separate accepted clicks from attributed billable outcomes. Apply late corrections without erasing audit history. No. Network delay and retries reorder arrival. Use the declared event-time and attribution policy, including late and untrusted timestamps.

45-minute interview rubric

  1. 00–05: scope ad event and deduplicated event ledger.
  2. 05–12: identify the limiting resource and derive the domain workload above, retaining units and assumptions.
  3. 12–28: draw deduplicated event ledger, numbered writes and reads.
  4. 28–40: challenge recovery: Specify attribution windows and separate provisional from reconciled totals.
  5. 40–45: defend impression_id placement, observations and remaining assumptions.

Go deeper

  • Joining | Apache Flink · Primary document · nightlies.apache.org. Specify attribution windows and separate provisional from reconciled totals. Verified 2026-10-26.
  • Design | Apache Kafka · Primary document · kafka.apache.org. Specify attribution windows and separate provisional from reconciled totals. Verified 2026-10-26.
  • Introduction | Apache Kafka · Primary document · kafka.apache.org. Specify attribution windows and separate provisional from reconciled totals. Verified 2026-10-26.

Decision log

Specify attribution windows and separate provisional from reconciled totals.

Preserve ad event identity and deduplicated event ledger ownership.

Revisit changed workload, observations or recovery objectives.