Skip to content
Flink · Worked example

Use case: real-time fraud signals for a card issuer

A worked example with a made-up card issuer: Flink keeps per-card state and computes velocity, geography and merchant-pattern signals within the authorisation window, and publishes them for the fraud decision engine.

Card fraud has to be judged in the time it takes to authorise a payment: a fraction of a second, most of it spent on networks and on the decision itself. Within that budget, the decision engine needs context it can't compute from the authorisation request alone: how many times this card has been used in the last ten minutes, whether it was just used four hundred miles away, whether this merchant category is new for it. Computing that context fast and correctly is a stateful streaming problem, and a good fit for Flink.

This worked example shows a design we use. The issuer, its systems and its numbers are made up.

Example · Larchmont Card Services, a made-up card issuer

The starting point

Larchmont's fraud decision engine scores each authorisation with rules and a model. Its context features come from a database queried during the authorisation: counts over recent transactions, last location, merchant history. At peak, those queries are the slowest part of the decision, and some features are dropped when the database is under load. The fraud team wants the features computed continuously, ahead of time, so the decision only has to read them.

1. Key by card, keep state per card

Authorisation requests arrive on a Kafka topic, keyed by a card token. The Flink job keys the stream by card, so all of a card's events are processed by the same subtask, in order, with that card's state at hand. Card profiles (home region, usual merchant categories, limits) come from a compacted topic and are joined as state, so the job never calls a database per event.

2. Three families of signals

  • Velocity: number and total amount of authorisations in the last ten minutes and the last hour, per card. Sliding windows would emit results for every slide; a KeyedProcessFunction with a small list of recent events and event-time timers gives an up-to-date answer on every authorisation instead.
  • Geography: distance and time since the card's last card-present authorisation, and the implied travel speed. One value of state per card.
  • Merchant pattern: whether the merchant category is new for the card, and sequences such as several small "test" charges followed by a large one, which Flink CEP can express as a pattern over the card's events.
// per card: a running window of recent authorisations, cleaned up by an event-time timer
class VelocityFunction extends KeyedProcessFunction<String, Auth, Signal> {
  ListState<Auth> recent;   // last hour of this card's authorisations

  void processElement(Auth a, Context ctx, Collector<Signal> out) {
    recent.add(a);
    long tenMin = countSince(recent, a.time - 10 * 60_000);
    out.collect(Signal.velocity(a.authId, a.card, tenMin, sumSince(recent, a.time - 3_600_000)));
    ctx.timerService().registerEventTimeTimer(a.time + 3_600_000);   // forget it after an hour
  }
  void onTimer(long t, OnTimerContext ctx, Collector<Signal> out) {
    prune(recent, t - 3_600_000);
  }
}

A simplified sketch of the velocity signal. Production code bounds the state size and handles out-of-order events.

3. Latency first

The job is built for latency, not throughput:

  • Event time with a short out-of-orderness bound, so clean-up timers fire promptly and per-card state stays small; see event time and watermarks. The velocity function emits on every event rather than waiting for windows to close.
  • RocksDB state with enough memory that the working set of active cards stays in cache.
  • At-least-once output keyed by authorisation id. The decision engine reads the latest signal for an authorisation, so a duplicate after a recovery is harmless, and the job avoids waiting a checkpoint interval for transactional commits; see checkpoints and savepoints.
  • A fallback: if a signal hasn't arrived within the decision's time budget, the engine decides without it and records that it did.
Measure end to end. The number that matters is the time from the authorisation event entering Kafka to its signal being readable by the decision engine, at the 99th percentile, on the busiest hour. Measure it with timestamps carried through the pipeline, not with Flink's internal metrics alone.

4. State that stays bounded

Millions of cards means millions of keys. Every piece of per-card state has a clean-up rule: recent-event lists are pruned by timers, and state for cards not seen for months expires with state TTL. Without that, state grows forever and checkpoints and recovery slow down with it.

Testing signals before they matter

  • Unit tests with Flink's test harnesses drive a keyed function with events and watermarks and check its state and output, including timers firing.
  • Replays of recorded traffic check that the job produces the same signals in a replay as it did live, which only holds because it runs in event time.
  • Known cases: confirmed fraud cases from history, replayed to confirm the signals the fraud team expects actually appear.

Where scoring happens

Larchmont keeps the decision, rules and model, in its existing engine; Flink only computes features. Scoring inside Flink is possible and removes a hop, but it ties model releases to job deployments and puts the fraud team's release cycle on the streaming team's pipeline. Keeping the two apart was the simpler choice here.

5. Changing the signals safely

The fraud team changes features often. Each change is deployed from a savepoint, with explicit operator ids so state survives the change. New signals are first published to a shadow topic and compared with the decision engine's existing features before they are used.

Example · what changed at Larchmont

After the move

The decision engine now reads precomputed signals instead of querying the database during authorisation, and features are no longer dropped at peak. The same per-card state later powered a new signal (card-not-present attempts across several merchants within a minute) that the old database design couldn't compute in time.

All names and details are fictional.

Fraud signals need to be correct and fast; sensor analytics need to cope with data that arrives late. Compare the IoT use case.

How to decide if this design fits

  1. Are features computed by querying a database during a time-critical decision? That is the main signal.
  2. Can the decision tolerate a feature that is a fraction of a second old? Precomputed signals are always slightly behind the event they describe.
  3. Is there a fallback when a signal is missing? Without one, the streaming job becomes part of the authorisation path's availability.

Questions we are often asked

Does the job handle card numbers?

In this design the stream is keyed by a card token, not the card number, which keeps the job's state and topics free of raw card data. Whether that is enough for your compliance scope is a question for your PCI assessor; treat this as general information.

Why not exactly-once output?

Exactly-once Kafka output becomes visible only when a checkpoint completes, which would add the checkpoint interval to every signal's latency. Duplicates are harmless here because the decision engine reads the latest signal per authorisation.

Building or rescuing a Flink job?

The Flink POD designs, builds and operates Apache Flink pipelines: event time, state, checkpoints, Kubernetes and the tuning that keeps them fast, inside your environment.

Flink POD

Keep reading

Back to blog