Fraud Detection with the DataStream API

Apache Flink offers a DataStream API for building robust, stateful streaming applications. It provides fine-grained control over state and time, which allows for the implementation of advanced event-driven systems. In this step-by-step guide you’ll learn how to build a stateful streaming application with Flink’s DataStream API.

What Are You Building?

Credit card fraud is a growing concern in the digital age. Criminals steal credit card numbers by running scams or hacking into insecure systems. Stolen numbers are tested by making one or more small purchases, often for a dollar or less. If that works, they then make more significant purchases to get items they can sell or keep for themselves.

In this tutorial, you will build a fraud detection system for alerting on suspicious credit card transactions. Using a simple set of rules, you will see how Flink allows us to implement advanced business logic and act in real-time.

Prerequisites

This walkthrough assumes that you have some familiarity with Java or Scala, but you should be able to follow along even if you are coming from a different programming language.

Help, I’m Stuck!

If you get stuck, check out the community support resources. In particular, Apache Flink’s user mailing list is consistently ranked as one of the most active of any Apache project and a great way to get help quickly.

How to Follow Along

If you want to follow along, you will require a computer with:

  • Java 8 or 11
  • Maven

A provided Flink Maven Archetype will create a skeleton project with all the necessary dependencies quickly, so you only need to focus on filling out the business logic. These dependencies include flink-streaming-java which is the core dependency for all Flink streaming applications and flink-walkthrough-common that has data generators and other classes specific to this walkthrough.

Java

  1. $ mvn archetype:generate \
  2. -DarchetypeGroupId=org.apache.flink \
  3. -DarchetypeArtifactId=flink-walkthrough-datastream-java \
  4. -DarchetypeVersion=1.14.4 \
  5. -DgroupId=frauddetection \
  6. -DartifactId=frauddetection \
  7. -Dversion=0.1 \
  8. -Dpackage=spendreport \
  9. -DinteractiveMode=false

Scala

  1. $ mvn archetype:generate \
  2. -DarchetypeGroupId=org.apache.flink \
  3. -DarchetypeArtifactId=flink-walkthrough-datastream-scala \
  4. -DarchetypeVersion=1.14.4 \
  5. -DgroupId=frauddetection \
  6. -DartifactId=frauddetection \
  7. -Dversion=0.1 \
  8. -Dpackage=spendreport \
  9. -DinteractiveMode=false

You can edit the groupId, artifactId and package if you like. With the above parameters, Maven will create a folder named frauddetection that contains a project with all the dependencies to complete this tutorial. After importing the project into your editor, you can find a file FraudDetectionJob.java (or FraudDetectionJob.scala) with the following code which you can run directly inside your IDE. Try setting break points through out the data stream and run the code in DEBUG mode to get a feeling for how everything works.

Java

FraudDetectionJob.java

  1. package spendreport;
  2. import org.apache.flink.streaming.api.datastream.DataStream;
  3. import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
  4. import org.apache.flink.walkthrough.common.sink.AlertSink;
  5. import org.apache.flink.walkthrough.common.entity.Alert;
  6. import org.apache.flink.walkthrough.common.entity.Transaction;
  7. import org.apache.flink.walkthrough.common.source.TransactionSource;
  8. public class FraudDetectionJob {
  9. public static void main(String[] args) throws Exception {
  10. StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
  11. DataStream<Transaction> transactions = env
  12. .addSource(new TransactionSource())
  13. .name("transactions");
  14. DataStream<Alert> alerts = transactions
  15. .keyBy(Transaction::getAccountId)
  16. .process(new FraudDetector())
  17. .name("fraud-detector");
  18. alerts
  19. .addSink(new AlertSink())
  20. .name("send-alerts");
  21. env.execute("Fraud Detection");
  22. }
  23. }

FraudDetector.java

  1. package spendreport;
  2. import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
  3. import org.apache.flink.util.Collector;
  4. import org.apache.flink.walkthrough.common.entity.Alert;
  5. import org.apache.flink.walkthrough.common.entity.Transaction;
  6. public class FraudDetector extends KeyedProcessFunction<Long, Transaction, Alert> {
  7. private static final long serialVersionUID = 1L;
  8. private static final double SMALL_AMOUNT = 1.00;
  9. private static final double LARGE_AMOUNT = 500.00;
  10. private static final long ONE_MINUTE = 60 * 1000;
  11. @Override
  12. public void processElement(
  13. Transaction transaction,
  14. Context context,
  15. Collector<Alert> collector) throws Exception {
  16. Alert alert = new Alert();
  17. alert.setId(transaction.getAccountId());
  18. collector.collect(alert);
  19. }
  20. }

Scala

FraudDetectionJob.scala

  1. package spendreport
  2. import org.apache.flink.streaming.api.scala._
  3. import org.apache.flink.walkthrough.common.sink.AlertSink
  4. import org.apache.flink.walkthrough.common.entity.Alert
  5. import org.apache.flink.walkthrough.common.entity.Transaction
  6. import org.apache.flink.walkthrough.common.source.TransactionSource
  7. object FraudDetectionJob {
  8. @throws[Exception]
  9. def main(args: Array[String]): Unit = {
  10. val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment
  11. val transactions: DataStream[Transaction] = env
  12. .addSource(new TransactionSource)
  13. .name("transactions")
  14. val alerts: DataStream[Alert] = transactions
  15. .keyBy(transaction => transaction.getAccountId)
  16. .process(new FraudDetector)
  17. .name("fraud-detector")
  18. alerts
  19. .addSink(new AlertSink)
  20. .name("send-alerts")
  21. env.execute("Fraud Detection")
  22. }
  23. }

FraudDetector.scala

  1. package spendreport
  2. import org.apache.flink.streaming.api.functions.KeyedProcessFunction
  3. import org.apache.flink.util.Collector
  4. import org.apache.flink.walkthrough.common.entity.Alert
  5. import org.apache.flink.walkthrough.common.entity.Transaction
  6. object FraudDetector {
  7. val SMALL_AMOUNT: Double = 1.00
  8. val LARGE_AMOUNT: Double = 500.00
  9. val ONE_MINUTE: Long = 60 * 1000L
  10. }
  11. @SerialVersionUID(1L)
  12. class FraudDetector extends KeyedProcessFunction[Long, Transaction, Alert] {
  13. @throws[Exception]
  14. def processElement(
  15. transaction: Transaction,
  16. context: KeyedProcessFunction[Long, Transaction, Alert]#Context,
  17. collector: Collector[Alert]): Unit = {
  18. val alert = new Alert
  19. alert.setId(transaction.getAccountId)
  20. collector.collect(alert)
  21. }
  22. }

Breaking Down the Code

Let’s walk step-by-step through the code of these two files. The FraudDetectionJob class defines the data flow of the application and the FraudDetector class defines the business logic of the function that detects fraudulent transactions.

We start describing how the Job is assembled in the main method of the FraudDetectionJob class.

The Execution Environment

The first line sets up your StreamExecutionEnvironment. The execution environment is how you set properties for your Job, create your sources, and finally trigger the execution of the Job.

Java

  1. StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

Scala

  1. val env = StreamExecutionEnvironment.getExecutionEnvironment

Creating a Source

Sources ingest data from external systems, such as Apache Kafka, Rabbit MQ, or Apache Pulsar, into Flink Jobs. This walkthrough uses a source that generates an infinite stream of credit card transactions for you to process. Each transaction contains an account ID (accountId), timestamp (timestamp) of when the transaction occurred, and US$ amount (amount). The name attached to the source is just for debugging purposes, so if something goes wrong, we will know where the error originated.

Java

  1. DataStream<Transaction> transactions = env
  2. .addSource(new TransactionSource())
  3. .name("transactions");

Scala

  1. val transactions: DataStream[Transaction] = env
  2. .addSource(new TransactionSource)
  3. .name("transactions")

Partitioning Events & Detecting Fraud

The transactions stream contains a lot of transactions from a large number of users, such that it needs to be processed in parallel by multiple fraud detection tasks. Since fraud occurs on a per-account basis, you must ensure that all transactions for the same account are processed by the same parallel task of the fraud detector operator.

To ensure that the same physical task processes all records for a particular key, you can partition a stream using DataStream#keyBy. The process() call adds an operator that applies a function to each partitioned element in the stream. It is common to say the operator immediately after a keyBy, in this case FraudDetector, is executed within a keyed context.

Java

  1. DataStream<Alert> alerts = transactions
  2. .keyBy(Transaction::getAccountId)
  3. .process(new FraudDetector())
  4. .name("fraud-detector");

Scala

  1. val alerts: DataStream[Alert] = transactions
  2. .keyBy(transaction => transaction.getAccountId)
  3. .process(new FraudDetector)
  4. .name("fraud-detector")

Outputting Results

A sink writes a DataStream to an external system; such as Apache Kafka, Cassandra, and AWS Kinesis. The AlertSink logs each Alert record with log level INFO, instead of writing it to persistent storage, so you can easily see your results.

Java

  1. alerts.addSink(new AlertSink());

Scala

  1. alerts.addSink(new AlertSink)

The Fraud Detector

The fraud detector is implemented as a KeyedProcessFunction. Its method KeyedProcessFunction#processElement is called for every transaction event. This first version produces an alert on every transaction, which some may say is overly conservative.

The next steps of this tutorial will guide you to expand the fraud detector with more meaningful business logic.

Java

  1. public class FraudDetector extends KeyedProcessFunction<Long, Transaction, Alert> {
  2. private static final double SMALL_AMOUNT = 1.00;
  3. private static final double LARGE_AMOUNT = 500.00;
  4. private static final long ONE_MINUTE = 60 * 1000;
  5. @Override
  6. public void processElement(
  7. Transaction transaction,
  8. Context context,
  9. Collector<Alert> collector) throws Exception {
  10. Alert alert = new Alert();
  11. alert.setId(transaction.getAccountId());
  12. collector.collect(alert);
  13. }
  14. }

Scala

  1. object FraudDetector {
  2. val SMALL_AMOUNT: Double = 1.00
  3. val LARGE_AMOUNT: Double = 500.00
  4. val ONE_MINUTE: Long = 60 * 1000L
  5. }
  6. @SerialVersionUID(1L)
  7. class FraudDetector extends KeyedProcessFunction[Long, Transaction, Alert] {
  8. @throws[Exception]
  9. def processElement(
  10. transaction: Transaction,
  11. context: KeyedProcessFunction[Long, Transaction, Alert]#Context,
  12. collector: Collector[Alert]): Unit = {
  13. val alert = new Alert
  14. alert.setId(transaction.getAccountId)
  15. collector.collect(alert)
  16. }
  17. }

Writing a Real Application (v1)

For the first version, the fraud detector should output an alert for any account that makes a small transaction immediately followed by a large one. Where small is anything less than $1.00 and large is more than $500. Imagine your fraud detector processes the following stream of transactions for a particular account.

Fraud Transaction

Transactions 3 and 4 should be marked as fraudulent because it is a small transaction, $0.09, followed by a large one, $510. Alternatively, transactions 7, 8, and 9 are not fraud because the small amount of $0.02 is not immediately followed by the large one; instead, there is an intermediate transaction that breaks the pattern.

To do this, the fraud detector must remember information across events; a large transaction is only fraudulent if the previous one was small. Remembering information across events requires state, and that is why we decided to use a KeyedProcessFunction. It provides fine-grained control over both state and time, which will allow us to evolve our algorithm with more complex requirements throughout this walkthrough.

The most straightforward implementation is a boolean flag that is set whenever a small transaction is processed. When a large transaction comes through, you can simply check if the flag is set for that account.

However, merely implementing the flag as a member variable in the FraudDetector class will not work. Flink processes the transactions of multiple accounts with the same object instance of FraudDetector, which means if accounts A and B are routed through the same instance of FraudDetector, a transaction for account A could set the flag to true, and then a transaction for account B could set off a false alert. We could of course use a data structure like a Map to keep track of the flags for individual keys, however, a simple member variable would not be fault-tolerant and all its information be lost in case of a failure. Hence, the fraud detector would possibly miss alerts if the application ever had to restart to recover from a failure.

To address these challenges, Flink provides primitives for a fault-tolerant state that are almost as easy to use as regular member variables.

The most basic type of state in Flink is ValueState, a data type that adds fault tolerance to any variable it wraps. ValueState is a form of keyed state, meaning it is only available in operators that are applied in a keyed context; any operator immediately following DataStream#keyBy. A keyed state of an operator is automatically scoped to the key of the record that is currently processed. In this example, the key is the account id for the current transaction (as declared by keyBy()), and FraudDetector maintains an independent state for each account. ValueState is created using a ValueStateDescriptor which contains metadata about how Flink should manage the variable. The state should be registered before the function starts processing data. The right hook for this is the open() method.

Java

  1. public class FraudDetector extends KeyedProcessFunction<Long, Transaction, Alert> {
  2. private static final long serialVersionUID = 1L;
  3. private transient ValueState<Boolean> flagState;
  4. @Override
  5. public void open(Configuration parameters) {
  6. ValueStateDescriptor<Boolean> flagDescriptor = new ValueStateDescriptor<>(
  7. "flag",
  8. Types.BOOLEAN);
  9. flagState = getRuntimeContext().getState(flagDescriptor);
  10. }

Scala

  1. @SerialVersionUID(1L)
  2. class FraudDetector extends KeyedProcessFunction[Long, Transaction, Alert] {
  3. @transient private var flagState: ValueState[java.lang.Boolean] = _
  4. @throws[Exception]
  5. override def open(parameters: Configuration): Unit = {
  6. val flagDescriptor = new ValueStateDescriptor("flag", Types.BOOLEAN)
  7. flagState = getRuntimeContext.getState(flagDescriptor)
  8. }

ValueState is a wrapper class, similar to AtomicReference or AtomicLong in the Java standard library. It provides three methods for interacting with its contents; update sets the state, value gets the current value, and clear deletes its contents. If the state for a particular key is empty, such as at the beginning of an application or after calling ValueState#clear, then ValueState#value will return null. Modifications to the object returned by ValueState#value are not guaranteed to be recognized by the system, and so all changes must be performed with ValueState#update. Otherwise, fault tolerance is managed automatically by Flink under the hood, and so you can interact with it like with any standard variable.

Below, you can see an example of how you can use a flag state to track potential fraudulent transactions.

Java

  1. @Override
  2. public void processElement(
  3. Transaction transaction,
  4. Context context,
  5. Collector<Alert> collector) throws Exception {
  6. // Get the current state for the current key
  7. Boolean lastTransactionWasSmall = flagState.value();
  8. // Check if the flag is set
  9. if (lastTransactionWasSmall != null) {
  10. if (transaction.getAmount() > LARGE_AMOUNT) {
  11. // Output an alert downstream
  12. Alert alert = new Alert();
  13. alert.setId(transaction.getAccountId());
  14. collector.collect(alert);
  15. }
  16. // Clean up our state
  17. flagState.clear();
  18. }
  19. if (transaction.getAmount() < SMALL_AMOUNT) {
  20. // Set the flag to true
  21. flagState.update(true);
  22. }
  23. }

Scala

  1. override def processElement(
  2. transaction: Transaction,
  3. context: KeyedProcessFunction[Long, Transaction, Alert]#Context,
  4. collector: Collector[Alert]): Unit = {
  5. // Get the current state for the current key
  6. val lastTransactionWasSmall = flagState.value
  7. // Check if the flag is set
  8. if (lastTransactionWasSmall != null) {
  9. if (transaction.getAmount > FraudDetector.LARGE_AMOUNT) {
  10. // Output an alert downstream
  11. val alert = new Alert
  12. alert.setId(transaction.getAccountId)
  13. collector.collect(alert)
  14. }
  15. // Clean up our state
  16. flagState.clear()
  17. }
  18. if (transaction.getAmount < FraudDetector.SMALL_AMOUNT) {
  19. // set the flag to true
  20. flagState.update(true)
  21. }
  22. }

For every transaction, the fraud detector checks the state of the flag for that account. Remember, ValueState is always scoped to the current key, i.e., account. If the flag is non-null, then the last transaction seen for that account was small, and so if the amount for this transaction is large, then the detector outputs a fraud alert.

After that check, the flag state is unconditionally cleared. Either the current transaction caused a fraud alert, and the pattern is over, or the current transaction did not cause an alert, and the pattern is broken and needs to be restarted.

Finally, the transaction amount is checked to see if it is small. If so, then the flag is set so that it can be checked by the next event. Notice that ValueState<Boolean> has three states, unset (null), true, and false, because all ValueState’s are nullable. This job only makes use of unset (null) and true to check whether the flag is set or not.

Fraud Detector v2: State + Time = ❤️

Scammers don’t wait long to make their large purchases to reduce the chances their test transaction is noticed. For example, suppose you wanted to set a 1-minute timeout to your fraud detector; i.e., in the previous example transactions 3 and 4 would only be considered fraud if they occurred within 1 minute of each other. Flink’s KeyedProcessFunction allows you to set timers that invoke a callback method at some point in time in the future.

Let’s see how we can modify our Job to comply with our new requirements:

  • Whenever the flag is set to true, also set a timer for 1 minute in the future.
  • When the timer fires, reset the flag by clearing its state.
  • If the flag is ever cleared the timer should be canceled.

To cancel a timer, you have to remember what time it is set for, and remembering implies state, so you will begin by creating a timer state along with your flag state.

Java

  1. private transient ValueState<Boolean> flagState;
  2. private transient ValueState<Long> timerState;
  3. @Override
  4. public void open(Configuration parameters) {
  5. ValueStateDescriptor<Boolean> flagDescriptor = new ValueStateDescriptor<>(
  6. "flag",
  7. Types.BOOLEAN);
  8. flagState = getRuntimeContext().getState(flagDescriptor);
  9. ValueStateDescriptor<Long> timerDescriptor = new ValueStateDescriptor<>(
  10. "timer-state",
  11. Types.LONG);
  12. timerState = getRuntimeContext().getState(timerDescriptor);
  13. }

Scala

  1. @SerialVersionUID(1L)
  2. class FraudDetector extends KeyedProcessFunction[Long, Transaction, Alert] {
  3. @transient private var flagState: ValueState[java.lang.Boolean] = _
  4. @transient private var timerState: ValueState[java.lang.Long] = _
  5. @throws[Exception]
  6. override def open(parameters: Configuration): Unit = {
  7. val flagDescriptor = new ValueStateDescriptor("flag", Types.BOOLEAN)
  8. flagState = getRuntimeContext.getState(flagDescriptor)
  9. val timerDescriptor = new ValueStateDescriptor("timer-state", Types.LONG)
  10. timerState = getRuntimeContext.getState(timerDescriptor)
  11. }

KeyedProcessFunction#processElement is called with a Context that contains a timer service. The timer service can be used to query the current time, register timers, and delete timers. With this, you can set a timer for 1 minute in the future every time the flag is set and store the timestamp in timerState.

Java

  1. if (transaction.getAmount() < SMALL_AMOUNT) {
  2. // set the flag to true
  3. flagState.update(true);
  4. // set the timer and timer state
  5. long timer = context.timerService().currentProcessingTime() + ONE_MINUTE;
  6. context.timerService().registerProcessingTimeTimer(timer);
  7. timerState.update(timer);
  8. }

Scala

  1. if (transaction.getAmount < FraudDetector.SMALL_AMOUNT) {
  2. // set the flag to true
  3. flagState.update(true)
  4. // set the timer and timer state
  5. val timer = context.timerService.currentProcessingTime + FraudDetector.ONE_MINUTE
  6. context.timerService.registerProcessingTimeTimer(timer)
  7. timerState.update(timer)
  8. }

Processing time is wall clock time, and is determined by the system clock of the machine running the operator.

When a timer fires, it calls KeyedProcessFunction#onTimer. Overriding this method is how you can implement your callback to reset the flag.

Java

  1. public void onTimer(long timestamp, OnTimerContext ctx, Collector<Alert> out) {
  2. // remove flag after 1 minute
  3. timerState.clear();
  4. flagState.clear();
  5. }

Scala

  1. override def onTimer(
  2. timestamp: Long,
  3. ctx: KeyedProcessFunction[Long, Transaction, Alert]#OnTimerContext,
  4. out: Collector[Alert]): Unit = {
  5. // remove flag after 1 minute
  6. timerState.clear()
  7. flagState.clear()
  8. }

Finally, to cancel the timer, you need to delete the registered timer and delete the timer state. You can wrap this in a helper method and call this method instead of flagState.clear().

Java

  1. private void cleanUp(Context ctx) throws Exception {
  2. // delete timer
  3. Long timer = timerState.value();
  4. ctx.timerService().deleteProcessingTimeTimer(timer);
  5. // clean up all state
  6. timerState.clear();
  7. flagState.clear();
  8. }

Scala

  1. @throws[Exception]
  2. private def cleanUp(ctx: KeyedProcessFunction[Long, Transaction, Alert]#Context): Unit = {
  3. // delete timer
  4. val timer = timerState.value
  5. ctx.timerService.deleteProcessingTimeTimer(timer)
  6. // clean up all states
  7. timerState.clear()
  8. flagState.clear()
  9. }

And that’s it, a fully functional, stateful, distributed streaming application!

Final Application

Java

  1. import org.apache.flink.api.common.state.ValueState;
  2. import org.apache.flink.api.common.state.ValueStateDescriptor;
  3. import org.apache.flink.api.common.typeinfo.Types;
  4. import org.apache.flink.configuration.Configuration;
  5. import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
  6. import org.apache.flink.util.Collector;
  7. import org.apache.flink.walkthrough.common.entity.Alert;
  8. import org.apache.flink.walkthrough.common.entity.Transaction;
  9. public class FraudDetector extends KeyedProcessFunction<Long, Transaction, Alert> {
  10. private static final long serialVersionUID = 1L;
  11. private static final double SMALL_AMOUNT = 1.00;
  12. private static final double LARGE_AMOUNT = 500.00;
  13. private static final long ONE_MINUTE = 60 * 1000;
  14. private transient ValueState<Boolean> flagState;
  15. private transient ValueState<Long> timerState;
  16. @Override
  17. public void open(Configuration parameters) {
  18. ValueStateDescriptor<Boolean> flagDescriptor = new ValueStateDescriptor<>(
  19. "flag",
  20. Types.BOOLEAN);
  21. flagState = getRuntimeContext().getState(flagDescriptor);
  22. ValueStateDescriptor<Long> timerDescriptor = new ValueStateDescriptor<>(
  23. "timer-state",
  24. Types.LONG);
  25. timerState = getRuntimeContext().getState(timerDescriptor);
  26. }
  27. @Override
  28. public void processElement(
  29. Transaction transaction,
  30. Context context,
  31. Collector<Alert> collector) throws Exception {
  32. // Get the current state for the current key
  33. Boolean lastTransactionWasSmall = flagState.value();
  34. // Check if the flag is set
  35. if (lastTransactionWasSmall != null) {
  36. if (transaction.getAmount() > LARGE_AMOUNT) {
  37. //Output an alert downstream
  38. Alert alert = new Alert();
  39. alert.setId(transaction.getAccountId());
  40. collector.collect(alert);
  41. }
  42. // Clean up our state
  43. cleanUp(context);
  44. }
  45. if (transaction.getAmount() < SMALL_AMOUNT) {
  46. // set the flag to true
  47. flagState.update(true);
  48. long timer = context.timerService().currentProcessingTime() + ONE_MINUTE;
  49. context.timerService().registerProcessingTimeTimer(timer);
  50. timerState.update(timer);
  51. }
  52. }
  53. @Override
  54. public void onTimer(long timestamp, OnTimerContext ctx, Collector<Alert> out) {
  55. // remove flag after 1 minute
  56. timerState.clear();
  57. flagState.clear();
  58. }
  59. private void cleanUp(Context ctx) throws Exception {
  60. // delete timer
  61. Long timer = timerState.value();
  62. ctx.timerService().deleteProcessingTimeTimer(timer);
  63. // clean up all state
  64. timerState.clear();
  65. flagState.clear();
  66. }
  67. }

Scala

  1. import org.apache.flink.api.common.state.{ValueState, ValueStateDescriptor}
  2. import org.apache.flink.api.scala.typeutils.Types
  3. import org.apache.flink.configuration.Configuration
  4. import org.apache.flink.streaming.api.functions.KeyedProcessFunction
  5. import org.apache.flink.util.Collector
  6. import org.apache.flink.walkthrough.common.entity.Alert
  7. import org.apache.flink.walkthrough.common.entity.Transaction
  8. object FraudDetector {
  9. val SMALL_AMOUNT: Double = 1.00
  10. val LARGE_AMOUNT: Double = 500.00
  11. val ONE_MINUTE: Long = 60 * 1000L
  12. }
  13. @SerialVersionUID(1L)
  14. class FraudDetector extends KeyedProcessFunction[Long, Transaction, Alert] {
  15. @transient private var flagState: ValueState[java.lang.Boolean] = _
  16. @transient private var timerState: ValueState[java.lang.Long] = _
  17. @throws[Exception]
  18. override def open(parameters: Configuration): Unit = {
  19. val flagDescriptor = new ValueStateDescriptor("flag", Types.BOOLEAN)
  20. flagState = getRuntimeContext.getState(flagDescriptor)
  21. val timerDescriptor = new ValueStateDescriptor("timer-state", Types.LONG)
  22. timerState = getRuntimeContext.getState(timerDescriptor)
  23. }
  24. override def processElement(
  25. transaction: Transaction,
  26. context: KeyedProcessFunction[Long, Transaction, Alert]#Context,
  27. collector: Collector[Alert]): Unit = {
  28. // Get the current state for the current key
  29. val lastTransactionWasSmall = flagState.value
  30. // Check if the flag is set
  31. if (lastTransactionWasSmall != null) {
  32. if (transaction.getAmount > FraudDetector.LARGE_AMOUNT) {
  33. // Output an alert downstream
  34. val alert = new Alert
  35. alert.setId(transaction.getAccountId)
  36. collector.collect(alert)
  37. }
  38. // Clean up our state
  39. cleanUp(context)
  40. }
  41. if (transaction.getAmount < FraudDetector.SMALL_AMOUNT) {
  42. // set the flag to true
  43. flagState.update(true)
  44. val timer = context.timerService.currentProcessingTime + FraudDetector.ONE_MINUTE
  45. context.timerService.registerProcessingTimeTimer(timer)
  46. timerState.update(timer)
  47. }
  48. }
  49. override def onTimer(
  50. timestamp: Long,
  51. ctx: KeyedProcessFunction[Long, Transaction, Alert]#OnTimerContext,
  52. out: Collector[Alert]): Unit = {
  53. // remove flag after 1 minute
  54. timerState.clear()
  55. flagState.clear()
  56. }
  57. @throws[Exception]
  58. private def cleanUp(ctx: KeyedProcessFunction[Long, Transaction, Alert]#Context): Unit = {
  59. // delete timer
  60. val timer = timerState.value
  61. ctx.timerService.deleteProcessingTimeTimer(timer)
  62. // clean up all states
  63. timerState.clear()
  64. flagState.clear()
  65. }
  66. }

Expected Output

Running this code with the provided TransactionSource will emit fraud alerts for account 3. You should see the following output in your task manager logs:

  1. 2019-08-19 14:22:06,220 INFO org.apache.flink.walkthrough.common.sink.AlertSink - Alert{id=3}
  2. 2019-08-19 14:22:11,383 INFO org.apache.flink.walkthrough.common.sink.AlertSink - Alert{id=3}
  3. 2019-08-19 14:22:16,551 INFO org.apache.flink.walkthrough.common.sink.AlertSink - Alert{id=3}
  4. 2019-08-19 14:22:21,723 INFO org.apache.flink.walkthrough.common.sink.AlertSink - Alert{id=3}
  5. 2019-08-19 14:22:26,896 INFO org.apache.flink.walkthrough.common.sink.AlertSink - Alert{id=3}

Running in an IDE

Running the project in an IDE may result in a java.lang.NoClassDefFoundError exception. This is probably because you do not have all required Flink dependencies implicitly loaded into the classpath.

  • IntelliJ IDEA: Go to Run > Edit Configurations > Modify options > Select include dependencies with "Provided" scope. This run configuration will now include all required classes to run the application from within the IDE.