Streaming systems do not make time simple. Records arrive out of order, retries create old timestamps, partitions advance at different rates, and a join can have all of its records by processing time while still missing an event-time relationship. Correct joins begin with an explicit definition of event time and a policy for lateness.

Amazon MSK supplies the Kafka log. Kafka Streams and Flink supply stateful window operators. The distinction matters: Kafka stores ordered records per partition, while the processing engine tracks event-time progress, local state, and side outputs.

Processing time, event time, and timestamps

Processing time is the wall clock of the worker that reads a record. Event time is when the source says the business event happened. Use event time for billing windows, sessions, rate calculations, and temporal joins. Use processing time only for operational windows where arrival time is the intended meaning.

Every input should have:

{
  "event_id": "evt-90211",
  "account_id": "acct-7",
  "event_type": "payment_authorized",
  "event_time": "2019-09-14T14:03:11.240Z",
  "observed_at": "2019-09-14T14:03:12.781Z"
}

Configure the engine to extract event_time, reject impossible future values, and treat observed_at as a diagnostic field. Kafka Streams uses a TimestampExtractor; Flink uses a watermark strategy. A bad extractor can silently assign broker append time, so contract-test its behavior with out-of-order fixtures.

Watermarks and a bounded late policy

A watermark for time W states that the operator does not expect ordinary records with event time below W. It is an estimate, not proof. One partition with no records must not freeze every window indefinitely. Engines use idleness detection for that reason, but idleness settings create a trade-off between completion and correctness.

A common strategy bounds out-of-order delay:

watermark = max_event_time_seen - 60 seconds
window_end = event_time rounded to the next 5-minute boundary
allowed_lateness = 10 minutes

The window produces a first result when the watermark reaches its end. An engine may update that result while records are still allowed. After the window plus allowed lateness expires, later records are rejected, sent to a side output, or reprocessed through correction logic.

Timeline showing a five-minute window, watermark, grace period, early output, update, and rejected late record

The diagram separates two controls that are often confused. Grace reduces incomplete early joins. Allowed lateness keeps state and permits updates. Increasing either uses more state and memory; neither can compensate for an upstream source that is completely stalled.

Windowed joins

An order stream and payment stream cannot be joined simply by arrival. A stream-stream join chooses a window and a key. For “payment within 30 minutes after order”:

SELECT
  o.order_id,
  o.amount_cents,
  p.payment_id,
  p.status
FROM orders o
JOIN payments p
  ON o.order_id = p.order_id
 AND p.event_time >= o.event_time
 AND p.event_time < o.event_time + INTERVAL '30' MINUTE
EMIT CHANGES;

This SQL style is representative of Kafka Streams ksqlDB and similar engines. For portable production SQL, Flink can express the same temporal relationship with a windowed interval join:

CREATE TABLE orders (
  order_id STRING,
  amount_cents BIGINT,
  event_time TIMESTAMP_LTZ(3),
  WATERMARK FOR event_time AS event_time - INTERVAL '1' MINUTE
) WITH (
  'connector' = 'kafka',
  'topic' = 'orders.events',
  'properties.bootstrap.servers' = 'BROKER_LIST',
  'format' = 'avro'
);

CREATE TABLE payments (
  payment_id STRING,
  order_id STRING,
  status STRING,
  event_time TIMESTAMP_LTZ(3),
  WATERMARK FOR event_time AS event_time - INTERVAL '1' MINUTE
) WITH (
  'connector' = 'kafka',
  'topic' = 'payments.events',
  'properties.bootstrap.servers' = 'BROKER_LIST',
  'format' = 'avro'
);

SELECT o.order_id, p.payment_id, p.status
FROM orders o, payments p
WHERE o.order_id = p.order_id
  AND o.event_time BETWEEN p.event_time - INTERVAL '30' MINUTE
                       AND p.event_time + INTERVAL '1' MINUTE;

The join key must be identical on both sides. If orders.events has key order_id and payments.events has key payment_id, the engine must repartition one or both streams. Repartitioning creates internal topics, adds serialization and network cost, and requires a new partitioning key that preserves application semantics.

Kafka Streams implementation

For an application deployed on ECS, EKS, or EC2, a Kafka Streams stream-stream join sets the join window and retention:

KStream<String, Order> orders = builder.stream("orders.events");
KStream<String, Payment> payments = builder.stream("payments.events");

KStream<String, ReconciledOrder> joined = orders.join(
    payments,
    ReconciledOrder::from,
    JoinWindows.ofTimeDifferenceAndGrace(
        Duration.ofMinutes(30),
        Duration.ofMinutes(10)),
    StreamJoined.<String, Order, Payment>with(
        Serdes.String(), orderSerde, paymentSerde)
);

joined.to("reconciled.orders");

Choose table joins for latest state and stream joins for distinct events. A Kafka Streams KTable-KTable join reflects current keyed state and may emit updates or tombstones; it is not a substitute for a historical event correlation.

Retention must cover the join window plus grace and the maximum expected replay gap. A common mistake is to set state-store retention to exactly the window, then lose one side after a deployment or rebalance. Treat source retention, local/changelog retention, and grace as one recovery budget.

Late event test

A deterministic test is more useful than a dashboard screenshot. Inject:

window       12:00-12:05
event A      event_time=12:01, arrives=12:01
watermark    advances to 12:05
event B      event_time=12:04, arrives=12:08  # within 10-minute grace
event C      event_time=12:03, arrives=12:20  # outside state retention

Assertions:

  1. A contributes to the first window output.
  2. B updates the same window rather than a new one.
  3. C lands in the side output with original topic, partition, offset, and event time.
  4. replay of A+B is idempotent at the target.
  5. a stalled idle partition triggers idleness policy in the expected interval.

On Flink, use a ProcessFunction or window side output for late elements. Do not assert only row counts; assert the window boundaries and final value, because a dropped late element can still leave a plausible count.

State and failure recovery

Stateful operators keep current join buffers and checkpoints. A worker loss triggers state restore and then resumes from committed Kafka offsets. Flink checkpoints and Kafka Streams changelog topics have different operational forms, but the invariant is the same: state, input offsets, and output transaction must correspond to a recoverable point.

For Kafka sinks, transactional or idempotent output may reduce duplicates but does not repair a non-idempotent external side effect. For an S3 or relational sink, use a durable event ID and upsert, object version, or dedup key.

During a backlog:

  • watch source lag, watermark age, and p99 event-time lateness separately;
  • scale out only until partition parallelism is exhausted;
  • expect repartition topics to amplify internal throughput;
  • throttle historical replay if it competes with live windows.

Operational targets and trade-offs

Measure:

event-time latency = max(now - watermark_time, now - event_time)

Suggested alerts are:

  • watermark older than 2 times the grace interval for five minutes;
  • late-side-output rate above 1 percent of the source;
  • state size above 70 percent of forecast capacity;
  • checkpoint age above two configured checkpoint intervals;
  • join miss ratio changes more than three standard deviations from the same hourly baseline.

Short windows and low grace reduce state and latency but drop more legitimate records. Long grace handles delayed upstream systems at the cost of late decisions and larger RocksDB/state-backend storage. Tumbling windows provide fixed reporting boundaries; hopping and session windows describe overlapping or activity-driven behavior and retain more state. The correct choice is the one whose business lateness, output semantics, and recovery horizon have been written down and tested.