Kafka overview
Event stream, meet real-time engine
Event-based applications have succeeded in providing a path forward for traditional transactional workloads at scale. Many have replaced monolithic database systems, running business operations instead as event processors connected by pub/sub platforms like Kafka. These platforms offer delivery guarantees strong enough to support transactions and recovery, and they scale horizontally across many machines.
This transformation has created an opportunity. In monolithic systems, you typically see only the end state, which is the result of a transaction. Those systems don't usually expose how the transaction got there — including its inputs and the triggers that started it — as data that other applications can read.
In contrast, pub/sub systems capture the triggers, because the triggers are already modeled as events. Other applications, not only the main production systems, can read those same events, and adding another reader costs little.
Diagnostics transformed the practice of medicine in the 20th century as blood tests, imaging, endoscopy, and biopsies offered physicians an insider's view of a patient's body. Live data is bringing a similar revolution to business operations.
Analyzing these events poses a different challenge from running the transactions themselves. Event platforms decouple producers from consumers, so events no longer queue behind one monolithic system. Event flows multiply and adapt faster to changing operational needs. Kafka deployments carry a growing number of operational feeds, each connecting one system to another or a few systems to a few others.
The hard problem is no longer building scalable pipelines that model business operations. It is detecting trends in those feeds, distilling insights from them, and delivering those insights as derived feeds that executable models produce in real time. Since trends change quickly, a fast explore-model-deploy cycle is critical.
Enter Deephaven. Deephaven was born from the need for fast data-driven R&D cycles for quantitative finance in the capital markets industry.
In capital markets, success depends not only on the ability to innovate, but on the speed of innovation. Teams slow down when siloed people do data exploration, model fitting, backtesting, implementation, and deployment as separate activities, in languages and tools that don't mix. Having different representations for streaming and historical data only compounds the problem.
Deephaven built its engine for a world where feeds are fundamental and live and historical data share a common vocabulary. Deephaven provides one table operations library for both streams and static tables, in your language of choice. The same operations run in-process in the data engine or remotely from a client, and they use popular, interoperable data formats.
The rest of this page walks through the explore and model steps of the explore-model-deploy cycle on one example:
- Explore a historical Parquet capture of a Kafka feed and build a baseline from it.
- Consume the live feed with the same table operations, and flag live samples that depart from the baseline.
- See how the same code deploys, and what you can do with the resulting feed.
A Kafka example in Deephaven
Consider the problem of detecting anomalies in the use of a service running in the cloud. The service backend runs as many processes on a machine pool, and each process produces telemetry for the requests it serves. The metric of interest is service use: the number of requests received in each 10-second sampling interval. For the purpose of this example, we assume a consolidated Kafka feed exists that aggregates overall service use in 10-second intervals.
Each Kafka event belongs to a topic and a partition, and carries an offset, a timestamp, a key, and a value. See Kafka basic terms for what each of these means. A single event in this feed looks like this. The table leaves out the offset, which this example doesn't use:
| Topic | Partition | Timestamp | Key | Value |
|---|---|---|---|---|
ServiceUse | 0 | t0 | MySvcName | TotalRequests |
TotalRequests above indicates the total number of requests received across all machines in the single 10-second period defined by t0. The Kafka value is an Avro record that stores this count as a 64-bit integer in its Value field.
A historical capture of the feed is also stored as Parquet files. The files form a key-value partitioned Parquet directory with one subdirectory per day, named like Date=2021-05-01. The capture adds a Date column to the columns listed above. Date is the partitioning column, and its values are strings in 'YYYY-MM-DD' form.
Our goal is to flag periods when overall service use falls outside a baseline of expected use. To define that baseline, we first explore the historical data.
Explore historical data
We begin by exploring historical data in the Deephaven IDE console. We load the historical data with the two lines of Python below:
This defines a Deephaven table called svc_use and opens it as a separate panel in the IDE, initially showing the first rows of the table. The where filter keeps only the rows for MySvcName, the same service that we later filter the live feed to.
The tabular view is useful to get an initial sense of the data. Scrolling through the view stays responsive, even though the capture holds one row every 10 seconds for many months.
read does not read all the data from the Parquet files. It loads only the metadata. Deephaven loads table data into memory only when a downstream operation pulls rows, such as scrolling through a table view or computing a derived table. The where filter in the same line is one such operation: it reads the Key column to find the matching rows, but no other column.
We push the scrollbar to the end of the available range to look at the most recent data. The numbers look comfortably bigger than what we saw in the first block of rows, which reflects organic growth in user adoption for our service. We expect this growth. What we want to flag is use that departs from the expected pattern, not the growth itself.
After a bit more browsing, we switch to a graphical view for more perspective. We want a line graph of the most recent months of data, so we filter on the Date partitioning column. Replace the date below with one about four months before your latest data:
With the panel for this new table selected, we click Table Options and pick Chart Builder from the menu. A simple line chart is enough for now. The graph shows marked seasonality. It looks like a "time of day, day of week" pattern. To confirm our guess, we define a derived table adding a few columns:
Secs is the event timestamp in epoch seconds, truncated to the start of its 10-second sampling period. The four-week window in Build a baseline filters on it. OrdinalDay and OrdinalWeek number the days and weeks since the Unix epoch, and OrdinalWeek later groups the samples by week.
SecondsInDay and DayOfWeek are the keys that later match each live sample to its baseline:
- Both use the time zone
TZ. - The
trueargument makessecondOfDaycount seconds by local clock time, so a sample at a given local time gets the same keys on either side of a daylight saving time change. dayOfWeekValuereturns the day of the week as a number.SecondsInDayis truncated to the start of its 10-second sampling period.
Like read, update_view does not compute its new columns up front:
- It computes a value only when a later operation, like a UI view or a chained computation, reads it.
- It doesn't copy the data in the pre-existing columns. It reads them from the base table.
- It calls the Python function
secsinside formulas again every time an operation reads aSecsvalue, including when it computesOrdinalDay.
If repeated calls to secs are costly, use update instead, which computes each value once and stores it.
Filtering this new table and graphing the results confirms the seasonality. Holidays are the exception, because their daily pattern resembles the one for Sundays. A production model would need to account for holidays, but this example ignores them.
To isolate the seasonality effects and more clearly observe the overall trend over time, we keep the Value and OrdinalWeek columns with view and total them by week with sum_by:
Graphing the weekly totals in by_week, either with the Chart Builder or in code with Deephaven Express, gives us a clear picture of the organic service-use growth over time. Weeks are counted in UTC from the Unix epoch, which was a Thursday, so each week runs from Thursday through Wednesday, UTC. The first and last weeks of the capture are usually partial, so their totals are lower. Ignore those two weeks when you read the trend.
Build a baseline
A complete baseline could overlay two simple models: one that captures the seasonality and one that captures the growth trend. This example builds only the seasonality model.
As a tentative baseline, we build the seasonality model as a derived table. For each time of day and day of week, it averages the matching samples from the last four weeks. That is usually four samples, one per week. After we consume the live feed, we compare each live sample to this baseline in Compare live data to the baseline.
Creating this table involves more aggregations and filtering. The example assumes the Parquet capture is current through the last midnight. The code below:
- Gets the current time with
dh_now. - Finds the last midnight in
TZwith the Java methodDateTimeUtils.atMidnight.deephaven.timehas no Python wrapper foratMidnight, so the code calls it throughjpy. - Keeps the samples from the four weeks before the last midnight with
where. - Averages them by the
DayOfWeekandSecondsInDaycolumns withagg_byandavg.
Consume the Kafka feed
We are ready now to get live samples to compare against. One call to consume ingests the Kafka feed into a live Deephaven table, and the result is powerful: the generated table looks and feels like our previous tables for historical data.
The consumer maps each event in the ServiceUse topic to columns:
- The Kafka key holds the service name and becomes the
ServiceNamecolumn. - The Kafka value is an Avro record, as the note under the sample event says. The consumer fetches its schema,
service_use_record, from the schema registry at theschema.registry.urladdress. The record'sValuefield becomes theValuecolumn. - The event's partition, offset, and timestamp become the
KafkaPartition,KafkaOffset, andKafkaTimestampcolumns.KafkaTimestampholds the same field the historical capture stores asTimestamp.
For details on the Avro format, see Read Kafka topic in Avro format. The code below creates the live table:
The code runs in three stages:
- The consumer produces a blink table, which keeps only the rows from the current update cycle.
- The
wherefilter runs on the blink table. Rows for other services never reach the next stage and disappear at the end of the cycle. blink_to_append_onlykeeps every matching row across cycles, solive_useaccumulates everyMySvcNamesample consumed since the table was created.
Compare live data to the baseline
Now we are ready to decorate the live data with the four-week average svc_use_last4weeks_avg from Build a baseline. First, we derive the join-key columns DayOfWeek and SecondsInDay from the KafkaTimestamp column:
The operation above does a natural join between the live table and the static table of historical averages. The join matches each live row to its baseline by DayOfWeek and SecondsInDay, and updates its result incrementally as new rows arrive in the live table. The code then adds PredictedDiff and PredictedPct, which compare each value to its baseline.
Finally, we add a where filter that keeps only the rows where the sample differs from the baseline by more than 5%:
use_anomalies is a live table of flagged samples. Each time a new MySvcName event arrives that differs from its baseline by more than 5%, a row appears in it.
How the live tables behave
Three points about live tables matter in this example:
- Live tables change as new data arrives. Each
MySvcNameevent that the consumer reads from the Kafka topic appears inlive_use. - Live tables and static tables share one table API. The
update_viewandwherecalls above are the same operations the historical exploration used, andnatural_joinjoins the live table to a static table with the same call that joins two static tables. Blink tables don't support a few operations. - Tables derived from live tables by most query operations are also live. Deephaven updates them incrementally where it can, applying the rows added, modified, or removed in the parent table to the previous result instead of recomputing from scratch. For example, the
wherefilter that producesuse_anomaliesevaluates only newly arrived rows, rather than refiltering every row thatblink_to_append_onlyhas kept. See the Deephaven table update model for details.
From exploration to modeling to deployment
The Kafka example built a model that flags service-use anomalies by comparing live Kafka samples to a four-week historical average. The next step is to implement and deploy production-quality code that gives the organization a live feed from that model.
Traditionally, as the introduction notes, that step is costly:
- The work changes languages, tools, and processes, and often passes from one person to another. Each change adds friction and cost.
- Every later model refinement or bug fix pays those costs again.
- Separate codebases for modeling and deployment raise the question of whether they implement the same thing, and teams seldom test for it.
But what if the code we wrote to model the problem could also run the production feed? It can. Save the same chain of query operations as a script and run it with Deephaven's Application Mode.
A long-running feed needs two changes that the example skips:
- Refresh the baseline on a schedule. The script computes
LAST_MIDNIGHTonce, when it runs, so the four-week window doesn't move forward on its own. The capture is read once as a static table, so each rebuild must re-read the capture to pick up newly captured files, as well as recomputeLAST_MIDNIGHTand the average. A function-generated table can run that rebuild on an interval. Each refresh updates the averages thatnatural_joinattaches to rows already in the live table, so rows can enter or leaveuse_anomalieswithout a new Kafka event. - Bound the live table.
blink_to_append_onlykeeps every row it receives. To bound it, applyring_tableto the filtered blink table fromconsumein place ofblink_to_append_only. The resulting ring table keeps only the latest rows. A ring table built fromlive_usewould not help, becauselive_useitself still keeps every row.
From live feed to action
What can we do with a feed in Deephaven? We can publish derived feeds, build dashboards that inform decisions, and take action from code.
- Publish a live table as a Kafka topic with
produce, or let another Deephaven server subscribe to it. Barrage, Deephaven's extension of the Arrow Flight protocol, carries the table update model over the network. Read more in the Deephaven Core API concept guide. - Script dashboards in the Deephaven IDE with
deephaven.ui, combining graphs, tables, and interactive elements such as filter selection widgets and buttons that run arbitrary code. Deephaven's dashboarding draws on its experience with risk modeling and compliance monitoring in capital markets. - Import other libraries for your language to act on the feed, because your code runs inside the Deephaven data engine. Define and monitor metrics against tolerance thresholds and trigger alerts in your organization's incident response platform. Send notifications to a messaging application. Place orders in an automated ordering system.
Why use Deephaven with Kafka
- Explore interactively, build models, and ship the same code. Prototyping a Kafka application in Deephaven also produces the code you deploy.
- Use one compute model for live and historical data.
- Build complex answers from the bottom up out of the results of smaller queries.
- Express intermediate results as tables for the clarity of your model. Operations such as
whereandupdate_viewreuse their parent table's column data instead of copying it. - Process streams without explicitly handling batches and time windows.
- Call your own code from inside a query's formulas, not only before or after a query runs. Your code runs in the data engine instead of moving data to your client and back.
- Run table operations as a script in the engine, or send them from a Deephaven client application to run on the server. See the Deephaven Core API concept guide.
Related documentation
- Kafka basic terms
- Deephaven's table types
- Table operations overview
- Incremental update model
- Designing the Deephaven Core API
- What is Barrage?
- Connect to a Kafka stream
- Write your own custom parser for Kafka
- Read Parquet files into Deephaven tables
- Chart Builder
- Deephaven Express
deephaven.ui- Multi-aggregation
- Filter table data
- Formulas
- Application Mode
- Generate tables with Python functions
- Use jpy
agg_byavgblink_to_append_onlyconsumedayOfWeekValuedh_nownatural_joinproducereadring_tablesecondOfDaysum_byto_j_time_zoneupdateupdate_viewviewwhereconsumerPydocproducerPydocparquetPydocstreamPydoctimePydocDateTimeUtilsJavadoc
Deephaven provides a suite of tools that makes Kafka integration easy.