<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tony Kambourakis on Medium]]></title>
        <description><![CDATA[Stories by Tony Kambourakis on Medium]]></description>
        <link>https://medium.com/@tonykambo?source=rss-869f12e14412------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*JjtxUGae_BSZ4AIj.jpg</url>
            <title>Stories by Tony Kambourakis on Medium</title>
            <link>https://medium.com/@tonykambo?source=rss-869f12e14412------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 01:46:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tonykambo/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Modernising Mission-Critical Mainframes: Analysis, Conversion, and the Path Forward]]></title>
            <link>https://tonykambo.medium.com/modernising-mission-critical-mainframes-analysis-conversion-and-the-path-forward-de777556af7f?source=rss-869f12e14412------2</link>
            <guid isPermaLink="false">https://medium.com/p/de777556af7f</guid>
            <category><![CDATA[code]]></category>
            <category><![CDATA[mainframe]]></category>
            <category><![CDATA[analysis]]></category>
            <category><![CDATA[mainframe-modernization]]></category>
            <category><![CDATA[legacy]]></category>
            <dc:creator><![CDATA[Tony Kambourakis]]></dc:creator>
            <pubDate>Tue, 02 Dec 2025 04:36:16 GMT</pubDate>
            <atom:updated>2025-12-02T04:36:16.741Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://www.linkedin.com/in/thomas-tschirschwitz-3229b32/">Thomas Tschirschwitz</a><em>, Principal Architect, IBM<br></em><a href="https://www.linkedin.com/in/ashley-levington-33aa823/">Ashley Levington</a>, <em>Mainframe Modernisation Architect, IBM<br></em><a href="https://www.linkedin.com/in/tonykambo/">Tony Kambourakis</a>, <em>Principal Architect, IBM</em></p><p>Across many large organisations sits the ever-working core system built on a mainframe, typically processing billions of calculations and transactions in both real-time and batch. The mainframe computer is a critical part of the organisation’s core business capability, often established decades earlier seeing various hardware upgrades along the way. However, the application software, likely written over 30+ years ago, rarely sees significant change given it comprises a programming language not usually seen outside the confines of these wondrous machines.</p><p>A regular activity amongst these organisations is legacy system modernisation that includes the treatment of various old platforms and data stores to operate in a hybrid cloud or fully cloud environment. This article focuses on the modernisation of legacy systems built on mainframe. It covers the challenges faced by organisations in the pursuit of addressing key risks with an ageing code base and the approach of transitioning to a modern IT landscape.</p><h3>Legacy Mainframe Challenges</h3><p>Whilst the modern mainframes are a technical wonder, running modern code base on a modern runtime is ideal. However, many banking, insurance, airline and government organisations are still running legacy code, data stores and integrations that tend to pose a number of challenges.</p><p>A legacy mainframe system typically exhibits the following characteristics:</p><ul><li><strong>Aged Code</strong> —<em> mainframe applications are 30 to 40 years </em>old, either originally bespoke or based on COTS that have been heavily customised.</li><li><strong>Business Critical</strong> — they ‘own’ key enterprise <em>data</em> (e.g. client, account, product) and control the key <em>business processes and business rules</em>, which often implement decades of <em>legislation</em> for organisations under regulated industries.</li><li><strong>Large Applications — </strong>a monolithic system comprising hundreds of applications tightly integrated through internal function calls and shared data stores, hundreds to thousands of screens/transactions and batch jobs, thousands of users and code bases with tens of millions of lines of code processing millions/billions of transactions per year.</li><li><strong>Large databases</strong> — over 1000 database tables, billions of records with decades of historical data.</li><li><strong>Highly integrated</strong> — hundreds or even thousands of external integrations.</li><li><strong>Arcane Technologies</strong> — built on runtime and data store technologies that have <em>extremely limited market skills availability</em> — e.g. CA Gen, Natural/Adabas, ADSO/IDMS, CA Ideal, IMS DB/DC.</li><li><strong>Historically flexible</strong> — decades of proven ability to meet new requirements due to well-engineered data models and application architectures</li><li><strong><em>Stable, secure and reliable</em> </strong>— often used for mission-critical workloads.</li><li><strong><em>Durable </em></strong>— Due to backward compatibility, applications written 40 years ago still run on<em> </em>latest<em> </em>IBM<em> </em>mainframe.</li><li><strong><em>Small support team</em></strong> — relatively low application support costs</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r8SAESfXARwF1i-MRSg4YA.png" /></figure><p>Whilst the mainframe system itself, in particular those based on recent hardware releases, are not the concern the applications themselves are the primary challenge.</p><p>The challenges with legacy mainframe applications include:</p><ul><li><strong>Extremely limited market for skills </strong>for arcane technologies such as CA Gen, leading to <em>critical key person dependencies</em></li><li><strong>Limited understanding of the application </strong>leading to<strong> </strong>low change velocity for new enhancements, often due to ignorance around <em>‘hidden’ business rules</em></li><li><strong>Excessive software licencing fees </strong>for arcane technologies such as CA Gen or Adabas/Natural, due to the ‘lock in’ nature of the technology</li><li><strong>‘Frozen’ technology capabilities </strong>as <em>vendors simply do not invest in new features </em>for arcane technologies such as CA Gen, Adabas/Natural, IDMS/ADSO etc</li><li><strong>(Perceived) high cost </strong>of <em>mainframe platform. Whilst the modern mainframe system can be maintained with a cost effective commercial model, it is the ageing applications and data stores that incur higher operational and licensing costs.</em></li></ul><h3>Lessons in Failure</h3><p>Organisations have attempted to address the problem through replacing the mainframe application with either a COTS or to custom build a replacement. These attempts often fail due to:</p><ul><li><strong>Vast application size</strong>; applications are the result of 100’s or 1000’s of person years of development, often driven by <em>legislative change</em>. Custom build (‘re-write’) requires <em>multi $100 million programs with 5–10 year durations</em>. For example we have seen applications with 5,000 screens and 10 million lines of code, resulting in re-write estimates exceeding 300,000 person days. Programs of this size rarely succeed and often don’t get past the business case phase.</li><li><strong>Inability to identify/specify existing business functions </strong>(aka ‘hidden business rules’) due to poor quality or lack of documentation; resulting in replacement systems that <em>do not meet ‘hidden’ requirements </em>and entire programs being written off <strong>.</strong></li><li><strong>Replacement with COTS failed</strong> because due to the bespoke nature of these ‘core business’ applications, <em>COTS products rarely support </em>legacy application <em>data model and/or function</em>, especially <em>country or state-specific legislation</em></li><li><strong><em>Massive change management challenge</em></strong>; applications are <em>used by entire organisation</em> and make ‘big bang’ implementations which change user experience/work practices of <em>entire organisation near </em>impossible. On the other hand, <em>incremental change takes too long, </em>requiring up to a decade of parallel running of both legacy and ‘new’, with complexities around reverse data synchronisation, temporary scaffolding, dual support teams etc.</li></ul><p>Having <strong>discounted the ‘replace’ option</strong>, many organisations<em> (grudgingly) accept </em>that they will <em>retain the legacy application for the ‘foreseeable future </em>‘. Therefore, what <em>can</em> be done to address the latent issues with an <em>acceptable cost, duration, and risk profile?</em></p><p>Modernisation strategies involving minimal impact include:</p><ul><li><strong>Accessing via APIs such such as z/OS Connect. </strong>Fastest way to unlock modern integration pattern with legacy system. Constrained by existing program functions and interfaces, typically designed for 3270 screens. Requires code changes to support expected modern API pattern otherwise burden on intermediary developers to implement a developer friendly façade.</li><li><strong>Replicate data to external data pipeline and store. This</strong> is a reasonable strategy where eventual consistency is acceptable. Read optimised store is established, events are published to support EDA. Write operations direct to system of record for simpler approach.</li></ul><p>However, these strategies <em>do not address most of the latent issues</em>.</p><p>An alternative approach is <strong><em>automated conversion &amp; refactoring </em></strong>which<em> </em>does address many issues with legacy applications with an acceptable cost, duration, security and risk profile<strong> . Conversion and refactoring of legacy applications to <em>contemporary technology</em></strong><em> </em>, e.g. Java/Angular/Spring/rdbms , is at the core of this approach. The approach <em>guarantees functional equivalence and similar performance </em>as the legacy application, while <em>empowering customers </em>to leverage the advantages of modern platforms and development practices for <em>future re-engineering.</em></p><p>Figure 2 below illustrates the overall approach for automated conversion of legacy technology to modern technology, typically Java/Angular with a relational database and application deployed to any platform, typically public cloud. Key aspects of the approach are (a) user experience preserved (b) all integrations preserved( c) no major code freeze required.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*881-0NLAFMS_zIBHI6l9rw.png" /></figure><p>There are various tools available to perform both analysis and conversation of code. One such set of tools are made by Modern Systems. We’ll use them for the example of the process to perform such conversion.</p><p>First step is to understand the existing codebase to help with the modernisation strategy.</p><h3>Code Analysis</h3><p>IBM-ModernSystems is a company that provides tools and services to analyse mainframe applications. Typically, as a first step to modernisation where the objective is to convert to a modern runtime or be used to gain enough insight of current implementation to support re-implementation.</p><p>The initial process is referred to as an assessment process utilising specific tools for specific legacy language and database code bases. It is a static code analysis toolset that parses and interprets the code base with the aim of generating a technical inventory of the application. The inventory is central to the assessment process and includes identification of business rules and various characteristics such as code complexity, lines of code, object types and relationships.</p><p>One of the key outputs of the Modern code analysis tool is a spreadsheet that contains the detailed breakdown of the code.</p><p>In this example the source code is written in NATURAL with an ADABAS database. The spreadsheet contains several tabs comprising a breakdown of the code. One such tab includes the types of objects identified including the counts, lines of code and whether they are used within by the applications. This leads to a reduction in the transformation scope, timeline, testing and cost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FqUTIY-GvvlwI5Y8qyd3jg.png" /></figure><p>The table above shows the object types including programs and subprograms (call/ called chain of programs), languages-various language entities, files, screens/mapsets, jobs/scripts, procedures and specialist scripting languages.</p><p>The spreadsheet is generated by the Modern Enterprise Application Viewer (EAV) assessment tool. It also includes the following outputs and insights:</p><ul><li><strong>Technical Inventory Spreadsheet</strong>: A primary output is a spreadsheet detailing various objects (programs, subprograms, data entities, and more). It includes language types, counts, and usage statistics.</li><li><strong>Object types and counts</strong> : The type of object, the number of them and the lines of code (used and not used) are listed as spreadsheet details and/or graphs.</li><li><strong>Activity within the application</strong>: An insight (notes alongside spreadsheet above) into the application based on the inventory, usage in the code and technical functionality.</li><li>The <strong>used and not used</strong> information is across all object types in the application which can result in <strong>decommissioning </strong>specific components and <strong>reducing technical debt</strong>.</li><li><strong>Code Complexity Metrics</strong>: The assessment provides metrics like Cyclomatic and Halstead code ratings that help estimate the required testing effort.</li><li><strong>Duplicate and Missing Components</strong>: The tool identifies duplicate objects, which can reduce technical debt, and missing components, providing feedback for further investigation.</li><li><strong>Program Call Chain/Dependencies</strong>: A report or graph illustrates program dependencies and interfaces — which provides a technical architecture overview.</li><li><strong>Asset Consumption</strong>: Insights into Create, Read, Update, and Delete (CRUD) actions on application assets are provided, helping understand how different assets interact.</li><li><strong>Application Interfaces</strong>: Information about intra- and inter-application integrations is presented, contributing to an architectural overview.</li><li><strong>Business Rule Identification</strong>: While the toolkit doesn’t interpret business rules, it can aid in isolating and graphically representing them, providing a pathway to understanding application logic (see next section on visualisation of this data)</li><li>Application objects/assets are also <strong>enumerated per sub-application</strong> or related applications so that a consolidated view of the technical composition of an application is presented and application ownership of an asset.</li><li>The various <strong>utilities</strong> (special function programs and/or user-defined), what they are used for and the number of them are also listed.</li></ul><p>The assessment enables the estimation of converting the database and language to a <strong>more modern runtime</strong> to then facilitate further <strong>modernisation strategies</strong> including migration to cloud, API identification, microservices, automated test case generation (using AI), code demystification, business rules extraction, DevOPs, real-time streaming events, re-architecting and re-platforming.</p><h3>Code Structure Complexity Visualisation</h3><p>The relationships between the various programs, subprograms and data entities are typically complex in monolithic mainframe applications. Whilst an application can be conceptually divided into domains of functionality the cross dependencies between the objects can be significant. To visualise these relationships the data from the IBM Modern Systems spreadsheet may be imported into a graph database to provide visualisations of these relationships.</p><p>For example, the following Cypher matches any program or subprogram that interacts with the Customer Search category.</p><pre>// 1️⃣ Match any PROGRAM or SUBPROGRAM interacting with Customer Search (either direction)<br>MATCH (a:Object)-[:CALLS]-(b:Object)<br>WHERE (a.category = &#39;Customer Search&#39; OR b.category = &#39;Customer Search&#39;)<br>AND a.dialect IN [&#39;NATURAL PROGRAM&#39;, &#39;NATURAL SUBPROGRAM&#39;]<br>AND b.dialect IN [&#39;NATURAL PROGRAM&#39;, &#39;NATURAL SUBPROGRAM&#39;]<br>AND a.category IS NOT NULL AND b.category IS NOT NULL<br><br>// 2️⃣ Return all interacting PROGRAM/SUBPROGRAM objects for graph view<br>RETURN DISTINCT a, b;</pre><p>Objects from the Account Ledgers, Legacy Providers, Navigation Menu, Account Notifications, Business Reporting, Customer Accounting and Shared Modules all integrate with Customer Search and in some cases between each other. It demonstrates there is no clean separation between domains of functionality within the mainframe applications that could be easily carved out for re-implementation under a phased approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TYXv_gkess8v1G8V_uLuMw.png" /></figure><h3>Code Conversion</h3><p>The following example describes an automated conversion process using IBM-MS tooling — the process involves Adabas/Natural as the codebase but it is a similar process for the other arcane legacy codebases like CA/GEN, IDMS etc</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WQaTleMWNLI42WdWYJ39XQ.png" /></figure><p>The architecture for the 3-tier solution is depicted as shown below. The logic layer which is the programs source essentially is automatically converted and generates JAVA runtime library executables. The presentation layer uses RESTFUL APIs to integrate with the JAVA source and the mapsets (screens) are represented in web browsers via Angular, HTML and JavaScript. The data is accessed via a Java Database Connector (JDBC) between the JAVA source and one of the 3 database choices Oracle, Db2 and/or SQL Server.</p><p>The conversion process results in a like-for-like functionality aiming to replicate the source code functionality as-is. The testing process (along with integrations) is iterative and applications/sub-applications are Unit, System , System Integrated, User Acceptance, Regression and Performance Tested.</p><p>This process consumes the majority of the effort of the conversion project (months). The conversion aims to test the application in its entirety and go-live (fix-on-fail approach) rather than release components of the application iteratively into Production. There will be a few months of co-existence and then there will be a progression with the converted application with no impact to business users i.e. same look and feel and outcomes of the current application but using more modern technology (codebase) and potentially the host platform too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*3hfRYbhxxmlQ2Ua8hkRgRA.png" /></figure><p>The result of the conversion process is a collection of code written for a modern runtime platform such as Java or C#. This code may then be deployed to either an on-prem environment or deployed to cloud and managed utilising your existing operations toolset.</p><h3>Additional Tools</h3><p>There are generative AI tools available to help understand the existing mainframe application. IBM’s ARC tool incorporates Gen AI powered autonomous agents to extract business rules from the legacy system. It generates pseudo code that it subsequently translates to business readable documents that may be stored in a knowledge base. This can be leveraged in gaining a deeper understanding of the existing application from which decisions can be made to maintain and extend the transformed code or undertake re-implementation. More on this in another article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de777556af7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Joining CDC generated event streams in Spark]]></title>
            <link>https://tonykambo.medium.com/joining-cdc-generated-event-streams-in-spark-15dfde188056?source=rss-869f12e14412------2</link>
            <guid isPermaLink="false">https://medium.com/p/15dfde188056</guid>
            <category><![CDATA[stream]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[mainframe]]></category>
            <category><![CDATA[cdc]]></category>
            <category><![CDATA[events]]></category>
            <dc:creator><![CDATA[Tony Kambourakis]]></dc:creator>
            <pubDate>Thu, 03 Apr 2025 04:48:04 GMT</pubDate>
            <atom:updated>2025-06-18T05:18:36.378Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://www.linkedin.com/in/tonykambo/">Tony Kambourakis</a>, <em>Principal Architect, IBM<br></em><a href="https://www.linkedin.com/in/sam-fursdon/"><em>Samuel Fursdon</em></a><em>, Solution Architect<br></em><a href="https://www.linkedin.com/in/jonathan-baldwin-70b59716a/">Jonathan Baldwin</a>, <em>Data Scientist, IBM<br></em><a href="https://www.linkedin.com/in/evan-kraak-3768661b9/"><em>Evan Kraak</em></a><em>, Technical Business Analyst</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ZqlLcip_W1F5yBLTtC70g.png" /></figure><h4>Overview</h4><p>In the previous article,<a href="https://medium.com/@tonykambo/approach-and-challenges-of-open-banking-apis-with-cqrs-and-core-banking-mainframe-5d7ace3dbca2"> <strong>Open Banking, Mainframe and CQRS</strong></a>, CDC was included as a mechanism for publishing events resulting from changes to a source system’s database. While this approach provides a simple and quick way of publishing events without the need to modify the source system or cause additional resource consumption on it, it does come with potential challenges. This article dives deeper into a specific scenario where we were unable to work around one of those challenges.</p><p>The key objective of CDC was to publish changes made to source systems, such as a core banking mainframe application, as events on a data stream such as Kafka. From there, a transformation pipeline would subscribe to the raw data events and transform them into business events that could be consumed by other applications. The business events would contain a selected set of stateful information from the updated record in the source system.</p><h4>Scenario</h4><p>CDC is double-edged sword when it comes to publishing business events. You can wire it up to a database and get access to data changes very quickly. The downside is that you end up publishing events that reflect the table schemas of the source system. Tables are typically designed to work for the application in persisting data in a way that supports rapid reads or writes for the application itself. The tables may be normalised to also support efficient database operations or the design of the application splits the data for a business object across multiple tables.</p><p>In this example scenario we have a bank account table with the following table design:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*W5yr1IY0sMw-FChRJTHwMg.png" /><figcaption>Figure 1 Account Table Design</figcaption></figure><p>The basic data pipeline comprises CDC detecting changes in the database and publishing to Kafka topics. Spark subscribes to these topics and perform the necessary joins across topics where required, transform to a canonical data format and then publish back to Kafka to a single account topic. The basic system is shown in the diagram below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*lid7VsRYUW_XFf2MaZtz4Q.png" /><figcaption>Figure 2 Basic System Flow</figcaption></figure><p>CDC is configured to publish changes from each table to its associated Kafka topic: <strong>account-primary</strong> and <strong>account-secondary.</strong></p><p>When an account is created, a row is added to both tables within a single commit. CDC will publish events to both topics with the “insert” operation. When subscribing to these topics spark will receive both events via separate data streams and joins them to then create a single business event, perhaps transforming them into a canonical data format. Spark publishes the <strong>account-create</strong> business event to an <strong>account</strong> topic.</p><p>The data pipeline is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j23lOxrivJ2Xy7J0_jjtnA.png" /><figcaption>Figure 3 Data Pipeline</figcaption></figure><p>There are multiple combinations of changes that are made to the Account Primary and Account Secondary tables. When an account is created an insert operation will be performed across both tables. However, updates will vary in that the Account Primary could be updated alone, or the Account Secondary could be updated alone. These additional combinations present challenge during the join step in Spark.</p><h4>Spark Joins</h4><p>As described above, suppose we had two Kafka streams from <strong>account-primary</strong> and <strong>account secondary</strong>. To consume these two streams, we first instantiate our SparkSession.</p><pre># Instantiate SparkSession<br>spark: SparkSession = SparkSession \<br>    .builder \<br>    .appName(&#39;CDCStreamJoinExample&#39;) \<br>    .getOrCreate()</pre><p>Now we read from the separate Kafka topics,</p><pre># Define Schema for Ingestion<br>account_primary_schema: StructType = StructType([<br>    StructField(&#39;account_id&#39;, StringType()),<br>    StructField(&#39;account_type&#39;, StringType()),<br>    StructField(&#39;balance&#39;, StringType()),<br>    StructField(&#39;purpose&#39;, StringType()),<br>    StructField(&#39;status&#39;, StringType()),<br>    StructField(&#39;change_date&#39;, IntegerType()),<br>    StructField(&#39;change_time&#39;, IntegerType()),<br>    StructField(&#39;cdc_operation&#39;, StringType()),<br>    StructField(&#39;cdc_timestamp&#39;, TimestampType()),<br>])<br><br><br>account_secondary_schema: StructType = StructType([<br>    StructField(&#39;account_id&#39;, StringType()),<br>    StructField(&#39;account_restriction&#39;, StringType()),<br>    StructField(&#39;restriction_date&#39;, IntegerType()),<br>    StructField(&#39;restriction_time&#39;, IntegerType()),<br>    StructField(&#39;cdc_operation&#39;, StringType()),<br>    StructField(&#39;cdc_timestamp&#39;, TimestampType())<br>])<br><br># Read Account Primary Stream<br>account_primary_df: DataFrame = spark \<br>    .readStream \<br>    .format(&#39;kafka&#39;) \<br>    .option(&#39;kafka.bootstrap.servers&#39;, &#39;localhost:9092&#39;) \<br>    .option(&#39;subscribe&#39;, &#39;account-primary&#39;) \<br>    .load() \<br>    .selectExpr(&#39;CAST(value AS STRING) AS value&#39;) \<br>    .select(<br>        from_json(col = &#39;value&#39;, schema = account_primary_schema).alias(&#39;json_value&#39;)<br>    ) \<br>    .select(&#39;json_value.*&#39;)<br><br><br># Read Account Secondary Stream<br>account_secondary_df: DataFrame = spark \<br>    .readStream \<br>    .format(&#39;kafka&#39;) \<br>    .option(&#39;kafka.bootstrap.servers&#39;, &#39;localhost:9092&#39;) \<br>    .option(&#39;subscribe&#39;, &#39;account-secondary&#39;) \<br>    .load() \<br>    .selectExpr(&#39;CAST(value AS STRING) AS value&#39;) \<br>    .select(<br>        from_json(col = &#39;value&#39;, schema = account_secondary_schema).alias(&#39;json_value&#39;)<br>    ) \<br>    .select(&#39;json_value.*&#39;)</pre><p>Our goal is to join the two event streams, this can be achieved by first defining a watermark on each stream. A watermark allows us to join records ingested by Spark in different microbatches. This is a useful feature when dealing with potentially late data, but is also required by Spark when performing certain kinds of stateful operations.</p><pre><br># Define Watermark on each DataFrame<br>account_primary_with_watermark = account_primary_df \<br>    .withWatermark(&#39;cdc_timestamp&#39;, &#39;5 seconds&#39;)<br><br>account_secondary_with_watermark = account_secondary_df \<br>    .withWatermark(&#39;cdc_timestamp&#39;, &#39;5 seconds&#39;)</pre><p>With this we can now join the two streams. For our purposes we want to match on ‘<strong>account_id</strong>’ and the ‘<strong>cdc_operation’</strong>. Additionally, as we want to consider cases where the individual source tables get updated independently, we perform a <strong>full outer join</strong> on both streams.</p><pre># Execute Stream-Stream Join<br>join_condition = (<br>    (account_primary_with_watermark.account_id == account_secondary_with_watermark.account_id) &amp;<br>    (account_primary_with_watermark.cdc_operation == account_secondary_with_watermark.cdc_operation) &amp;<br>    (account_primary_with_watermark.cdc_timestamp &gt;= account_secondary_with_watermark.cdc_timestamp - expr(&#39;interval 10 seconds&#39;)) &amp;<br>    (account_primary_with_watermark.cdc_timestamp &lt;= account_secondary_with_watermark.cdc_timestamp + expr(&#39;interval 10 seconds&#39;))<br>)<br><br><br>account_joined_df: DataFrame = account_primary_with_watermark \<br>    .join( <br>        account_secondary_with_watermark,<br>        join_condition,<br>        &#39;fullOuter&#39;<br>    )</pre><p>To fully commence the processing, and to see the output of the join we run the following:</p><pre>joined_query = account_joined_df \<br>    .writeStream \<br>    .outputMode(&#39;append&#39;) \<br>    .format(&#39;console&#39;) \<br>    .option(&#39;truncate&#39;, &#39;False&#39;) \<br>    .start()<br><br>joined_query.awaitTermination()</pre><p>Now with this active, we can investigate how this join behaves. Suppose with our Spark application active, a new account is created. Through Kafka, via CDC, we receive two records representing the inserts on the two source tables. Let’s assume we received the following two records:</p><pre>account_primary:  {&quot;account_id&quot;: &quot;12345&quot;, &quot;account_type&quot;: &quot;savings&quot;, &quot;balance&quot;: &quot;0.00&quot;, &quot;purpose&quot;: null, &quot;status&quot;: null, &quot;change_date&quot;: 40554, &quot;change_time&quot;: 40554, &quot;cdc_operation&quot;: &quot;INSERT&quot;, &quot;cdc_timestamp&quot;: &quot;2023-07-02T12:30:15&quot;}<br><br>account_secondary: {&quot;account_id&quot;: &quot;12345&quot;, &quot;account_restriction&quot;: &quot;limited&quot;, &quot;restriction_date&quot;: 0, &quot;restriction_time&quot;: 0, &quot;cdc_operation&quot;: &quot;INSERT&quot;, &quot;cdc_timestamp&quot;: &quot;2023-07-02T12:30:15&quot;}</pre><p>As we would anticipate the two records are joined, and the following is logged to the console:</p><pre>+----------+------------+-------+-------+------+-----------+-----------+-------------+-----------------------+----------+-------------------+----------------+----------------+-------------+-----------------------+<br>|account_id|account_type|balance|purpose|status|change_date|change_time|cdc_operation|cdc_timestamp          |account_id|account_restriction|restriction_date|restriction_time|cdc_operation|cdc_timestamp          |<br>+----------+------------+-------+-------+------+-----------+-----------+-------------+-----------------------+----------+-------------------+----------------+----------------+-------------+-----------------------+<br>|12345     |savings     |0.00   |null   |null  |40554      |40554      |INSERT       |2023-07-16 19:29:22.345|12345     |limited            |0               |0               |INSERT       |2023-07-16 19:29:22.346|<br>+----------+------------+-------+-------+------+-----------+-----------+-------------+-----------------------+----------+-------------------+----------------+----------------+-------------+-----------------------+</pre><p>Now suppose the same account is updated on the primary table. In this case we may receive the following record via CDC:</p><pre>account_primary: {&quot;account_id&quot;: &quot;12345&quot;, &quot;account_type&quot;: &quot;credit&quot;, &quot;balance&quot;: &quot;0.00&quot;, &quot;purpose&quot;: null, &quot;status&quot;: null, &quot;change_date&quot;: 40554, &quot;change_time&quot;: 40554, &quot;cdc_operation&quot;: &quot;UPDATE&quot;, &quot;cdc_timestamp&quot;: &quot;2023-07-02T12:30:17&quot;}</pre><p>However, in this scenario we notice that nothing is output by our join:</p><pre>+----------+------------+-------+-------+------+-----------+-----------+-------------+-------------+----------+-------------------+----------------+----------------+-------------+-------------+<br>|account_id|account_type|balance|purpose|status|change_date|change_time|cdc_operation|cdc_timestamp|account_id|account_restriction|restriction_date|restriction_time|cdc_operation|cdc_timestamp|<br>+----------+------------+-------+-------+------+-----------+-----------+-------------+-------------+----------+-------------------+----------------+----------------+-------------+-------------+</pre><p>If we continue to receive UPDATE records like this, from either topic, nothing will be output.</p><p>Spark is entering these records into stateful storage, holding them until it can find a matching record to successfully join with. These records will be held in state until a successful join occurs, which could take an indefinite amount of time beyond the watermark interval.</p><p>Continuing our example, if we publish a new account we will see two outputs, one for the new account and one for records previously held in state.</p><pre>+----------+------------+-------+-------+------+-----------+-----------+-------------+-----------------------+----------+-------------------+----------------+----------------+-------------+----------------------+<br>|account_id|account_type|balance|purpose|status|change_date|change_time|cdc_operation|cdc_timestamp          |account_id|account_restriction|restriction_date|restriction_time|cdc_operation|cdc_timestamp         |<br>+----------+------------+-------+-------+------+-----------+-----------+-------------+-----------------------+----------+-------------------+----------------+----------------+-------------+----------------------+<br>|99888     |savings     |0.00   |null   |null  |40554      |40554      |INSERT       |2023-07-22 23:14:48.109|99888     |limited            |0               |0               |INSERT       |2023-07-22 23:14:48.11|<br>+----------+------------+-------+-------+------+-----------+-----------+-------------+-----------------------+----------+-------------------+----------------+----------------+-------------+----------------------+<br><br>+----------+------------+-------+-------+------+-----------+-----------+-------------+-----------------------+----------+-------------------+----------------+----------------+-------------+-------------+<br>|account_id|account_type|balance|purpose|status|change_date|change_time|cdc_operation|cdc_timestamp          |account_id|account_restriction|restriction_date|restriction_time|cdc_operation|cdc_timestamp|<br>+----------+------------+-------+-------+------+-----------+-----------+-------------+-----------------------+----------+-------------------+----------------+----------------+-------------+-------------+<br>|12345     |credit      |0.00   |null   |null  |40554      |40554      |UPDATE       |2023-07-22 23:14:30.533|null      |null               |null            |null            |null         |null         |<br>+----------+------------+-------+-------+------+-----------+-----------+-------------+-----------------------+----------+-------------------+----------------+----------------+-------------+-------------+</pre><p>Hence, we can see that our UPDATE events are effectively blocked until a new account is generated. If the total frequency of new accounts being generated is low this means account updates will be delayed.</p><h4>Solution Alternatives</h4><p>The same issue was experienced when implementing stream joins using ksqlDB (see <a href="https://tonykambo.medium.com/challenges-with-ksqldb-non-joined-events-part-1-8ebf30b38b75">ksqlDB Non Joined Events</a>). Some alternatives considered include:</p><ul><li><strong>Modify the source system</strong> to publish events that are already combined. This may be viable if the source system is easily modifiable and is cost effective. The principle of avoiding burdening of the source system with additional processing removed this option.</li><li><strong>Configure CDC to perform a back query</strong>. CDC systems may be configured to retrieve additional data from the source database upon detecting a change. This may lead to a significant increase in load on the source system. This approach was implemented in some limited use cases, however, it became evident that race conditions resulted in the referenced data not being available in time for the CDC engine to make the call back. Further, it added significant burden to the DB to support these back queries for each change event, which violated our constraints.</li><li><strong>Configure stream processing code </strong>to retrieve additional data from cached source system data in flight. This may lead to race conditions where the data in the cache has not been updated quick enough to match the incoming event.</li><li><strong>Maintain state of each entity in an intermediary DB. </strong>The state of each table may be replicated to a separate database. When a change event occurs on any one of those tables (e.g. primary table), Spark may query the related tables (secondary tables) to assemble the full required state of the given object (i.e. account). This approach introduced race conditions whereby a given event may arrive prior to the related records arriving in the reference tables, resulting in either a failed join or an inconsistent state being joined to the change record.</li><li><strong>Bespoke stream processing code</strong> within Spark to identify non-joined conditions and introduce dummy joined events that help push through non-joined events of which the dummy events are subsequently filtered out. This is not an elegant solution and pollutes the event stream.</li><li><strong>ksqlDB with materialised views </strong>may be implemented to join from multiple streams however does incur performance overhead (see <a href="https://tonykambo.medium.com/joining-multiple-materialised-views-using-ksqldb-55c9def9de3a">Joining multiple materialised views using ksqlDB</a>).</li></ul><h4>Chosen Solution</h4><p>Another approach is to utilise database triggers. The database trigger is used to join required data from multiple tables into a single, intermediate table. CDC only monitors the intermediate table for changes, publishing a single pre-joined event to a single topic. This removes the need for cross-topic joins in Spark.</p><p>The database triggers are fired when either Primary or Secondary tables are updated. These tables are updated via a single transaction commit. Additional reference data from other tables may also be joined.</p><p>Separate triggers are established, one for the Primary and one for the Secondary account tables covering inserts, updates and deletes. Where both the Primary and Secondary tables are updated within a single transaction the trigger set on the Primary table is executed, joining the data from both tables.</p><p>Where the Secondary table is updated exclusively the Secondary trigger is set to only fire if only a specific set of attributes are changed indicating an exclusive Secondary table scenario. This avoids a double trigger where both the Primary and Secondary tables are updated under a single transaction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g9oUpDBN0zfc2grnEvrbaQ.png" /><figcaption>Figure 4 Database Trigger Join</figcaption></figure><p>It’s important to note that triggers execute synchronously with the transaction on the source tables. The trigger execution time is added as overhead to the original commit operation of the originating transaction within the system.</p><p>To avoid this overhead impacting the source system itself, the source system database may be replicated to a copy where the triggers may be executed without impacting the source system’s performance (see Figure 5).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*seW9XRCSAzDNyMghyMNyzw.png" /><figcaption>Figure 5 Externalised Replica System Flow</figcaption></figure><p>For efficiency, some CDC engines can condense a batch of individual source operations into a target operation that applies only the net result (e.g. if there are 3 updates to a given record within a batch of source operations, only a single update carrying the final state of the record following the 3rd update may be applied to the replica DB).</p><p>For transactional consistency with source, it is important that that this optimisation does not occur from the CDC engine as each of the three individual updates may carry change information that is important to the event consumer. Instead, this replication of the source database must be transactional — one source operation corresponds to one target operation in the replica database.</p><h4>Cautions</h4><p>Whilst the approach was ultimately successful in delivering an event streaming solution within the constraints of our use case, there are some drawbacks to consider.</p><ul><li><strong>Complexity: </strong>The example offered here were simplified to convey the logic behind the solution. In reality, the required (‘canonical’) state of an object to be produced in a business event may likely be carried by more than just a single primary and secondary table from a source system. Each source table that carries a component of the required state must have the necessary triggers attached to it if they can be independently changed, and each will need to write to an ever growing intermediate table.</li><li><strong>Fragility:</strong> The design is strongly coupled to the source system’s database and schema. Changes to this schema need to be reflected in the CDC tasks, the replicated tables (if replicated), the triggers, and the intermediate tables. Unexpected changes risk breaking the solution. Even expected changes may necessitate a re-sync of the intermediate tables (see below).</li><li><strong>Seeding and Re-Syncing the Intermediate tables: </strong>Assuming the solution is to be deployed against an already operational DB, a step will be required to initially seed the intermediate tables with the state of the referenced source tables before publishing change events from these intermediate tables. Later, if a re-seed is required (i.e. in response to a schema change or crash), it is complex to orchestrate this re-initialisation of the intermediate tables without missing or duplicating change events that would otherwise be published from those tables during that time.</li></ul><p>Ultimately, this solution was appropriate and its drawbacks acceptable given our use case and constraints with regard to source systems. However, there should be careful consideration as to whether those requirements and constrains are applicable (or at least negotiable) prior to embarking on a similar solution.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15dfde188056" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Challenges with ksqlDB non-joined events (Part 1)]]></title>
            <link>https://tonykambo.medium.com/challenges-with-ksqldb-non-joined-events-part-1-8ebf30b38b75?source=rss-869f12e14412------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ebf30b38b75</guid>
            <category><![CDATA[modernisation]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[ksqldb]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[events]]></category>
            <dc:creator><![CDATA[Tony Kambourakis]]></dc:creator>
            <pubDate>Fri, 29 Dec 2023 05:01:18 GMT</pubDate>
            <atom:updated>2023-12-29T05:01:18.099Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Change Data Capture (CDC) is often used as a relatively straight forward way of publishing events to Kafka based on changes to an application’s database. The events published reflect the internal table schemas and may prove challenging to process them, forming meaningful business events.</p><p>In this article, we’ll delve into a banking scenario where an account processing system utilises a database to store account details across two tables. With the first approach we’ll attempt to use ksqlDB stream to stream joins.</p><h3>ksqlDB Stream to Stream Joins</h3><p>ksqlDB can be used to join two streams that forms a single stream with combined data. The join may be established against matching values over a time interval. There is a scenario where a stream may not require an event to be matched with another event in the other stream. This is referred to as an non-joined event. In this section we will illustrate this scenario to observe ksqlDB’s behaviour.</p><p>The example will include two streams representing events related to banking accounts. Specifically this would be driven by CDC publishing events from changes to two tables containing account information. This internal schema may suit its application but proves to be challenging when attempting to derive business events from changes to the tables.</p><p>The objective is to publish account business events to a single stream reflecting account creation and account update events in strict order.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*ei98unrSr1qcHpfCVUvyvw.png" /><figcaption>Account Table Schemas</figcaption></figure><p>The table changes are published to their associated ksqlDB streams. When an account is created an insert is made to both tables, publishing an event to its associated stream. However, updates will vary in that the Account Info could be updated alone, or the Account Fraud could be updated alone, publishing single evens in either stream.</p><p>Two streams are created representing the feeds from CDC. The join condition will use the account identifier to match the events but we also need the CDC ‘operations’ to match as well. That is an event representing an insert operation in stream ‘<strong>account_info</strong>’ must be matched to an insert event in stream ‘<strong>fraud_detection_info’</strong> and not an update event.</p><p>As ksqlDB does not support multiple join conditions the stream key is set to the account Id and forms the join condition whilst the WHERE clause will be used to filter on only matching operations.</p><pre>CREATE STREAM account_info<br>(<br> accountId STRING KEY,<br> operation STRING,<br> productCode STRING,<br> balance DECIMAL(12, 2),<br> changeDateTime TIMESTAMP<br>)<br>WITH (<br> KAFKA_TOPIC=&#39;account_info_topic&#39;,<br> KEY_FORMAT=&#39;JSON&#39;,<br> VALUE_FORMAT=&#39;JSON&#39;,<br> PARTITIONS=3,<br> TIMESTAMP=&#39;changeDateTime&#39;<br>);<br><br>CREATE STREAM account_fraud_info<br>(<br> accountId STRING KEY,<br> operation STRING,<br> fraudStatus STRING,<br> accountRestriction STRING,<br> changeDateTime TIMESTAMP<br>)<br>WITH (<br> KAFKA_TOPIC=&#39;fraud_info_topic&#39;,<br> KEY_FORMAT=&#39;JSON&#39;,<br> VALUE_FORMAT=&#39;JSON&#39;,<br> PARTITIONS=3,<br> TIMESTAMP=&#39;changeDateTime&#39;<br>);</pre><p>The streams are joined using ksqlDB’s CREATE STREAM AS SELECT statement (1). CDC includes an <strong>operation</strong> field in the metadata it passes along with events it generates. The <strong>operation</strong> field indicates either an <strong>insert</strong> or <strong>update</strong> in the table. When matching events for the join, both the account identifier and the operation must match.</p><p>The statement uses a FULL OUTER JOIN to allow for either left-side or right-side nulls for non-joined events. That is, when an event is published to a stream where there is no joined event in the other stream it will be published to the joined stream with null values for the other side.</p><p>In addition we include a GRACE period that will alter the behaviour of the OUTER join by preventing non-joined events from being eagerly emitted, that is emitted upon initially receiving the events rather than waiting for the join window to complete.(2)</p><pre>CREATE STREAM accounts WITH (KAFKA_TOPIC=&#39;_accounts&#39;) AS<br> SELECT<br>  ROWKEY as joinKey,<br>  COALESCE(a.accountId, f.accountId) as accountId,<br>  a.productCode,<br>  a.operation as a_operation,<br>  a.balance,<br>  f.fraudStatus,<br>  f.accountRestriction,<br>  f.operation as f_operation,<br>  FORMAT_TIMESTAMP(FROM_UNIXTIME(a.rowtime), &#39;yyyy-MM-dd HH:mm:ss&#39;) AS accountEventTime,<br>  FORMAT_TIMESTAMP(FROM_UNIXTIME(f.rowtime), &#39;yyyy-MM-dd HH:mm:ss&#39;) AS fraudEventTime<br> FROM account_info a<br> FULL OUTER JOIN<br>  account_fraud_info f<br> WITHIN 30 SECONDS GRACE PERIOD 0 SECONDS<br> ON a.accountId = f.accountId<br> WHERE (a.operation IS NULL OR f.operation IS NULL OR a.operation = f.operation);</pre><p>Open ksqlDB CLI to observe the streams:</p><pre>SET &#39;auto.offset.reset&#39; = &#39;earliest&#39;;<br>SELECT * FROM accounts EMIT CHANGES;</pre><p>The example scenario will follow the timeline in the image below. This sequence includes non-joined events in both the account info stream and account fraud stream in addition to joined events across both streams.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jeHVkGEEa6yLPFDWV7VXMw.png" /><figcaption>Kafka stream-stream join timeline</figcaption></figure><p>Insert the initial record for account 8001 that results in a join between the account info and fraud details.</p><pre>INSERT INTO account_info (accountId, operation, productCode, balance, changeDateTime) <br>VALUES (&#39;8001&#39;, &#39;insert&#39;,&#39;10&#39;, 1000.00, &#39;2023-08-20T09:00:04&#39;);<br><br>INSERT INTO fraud_detection_info (accountId, operation, fraudStatus, accountRestriction, changeDateTime) <br>VALUES (&#39;8001&#39;, &#39;insert&#39;,&#39;CLEARED&#39;, &#39;NONE&#39;, &#39;2023-08-20T09:00:05&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ohYTr0ltCHIsRsQWNO-0g.png" /></figure><p>The next record for account 8002 is inserted and that results in a join between the account info and fraud details as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aE9T1oHngyhWCV29hOjz6g.png" /></figure><p>Subsequent inserts are made for updates to accounts 8003, 8004 and 8005 however none result in non-joined events being published to the joined stream.</p><pre>INSERT INTO account_info (accountId, operation, productCode, balance, changeDateTime) <br>VALUES (&#39;8003&#39;, &#39;update&#39;, &#39;12&#39;, 1500.00, &#39;2023-08-20T09:00:45&#39;);<br><br>INSERT INTO fraud_detection_info (accountId, operation, fraudStatus, accountRestriction, changeDateTime) <br>VALUES (&#39;8004&#39;, &#39;update&#39;, &#39;REVIEW&#39;, &#39;FROZEN&#39;,&#39;2023-08-20T09:01:50&#39;);<br><br>INSERT INTO account_info (accountId, operation, productCode, balance, changeDateTime) <br>VALUES (&#39;8005&#39;, &#39;update&#39;, &#39;10&#39;, 1500.00, &#39;2023-08-20T09:01:55&#39;);<br></pre><p>When an update event for account 8006 is inserted a non-joined event for account 8003 is published.</p><pre>INSERT INTO fraud_detection_info (accountId, operation, fraudStatus, accountRestriction, changeDateTime) <br>VALUES (&#39;8006&#39;, &#39;update&#39;,&#39;REVIEW&#39;, &#39;FROZEN&#39;,&#39;2023-08-20T09:02:50&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sL0_xD1MXLZcXcFOPboEzA.png" /></figure><p>The event for account 8003 comprises a right-side null, that is the fraud information does not exist and so all fraud attributes are set to null.</p><p>Whilst it is acceptable to receive null values for those attributes the issue is the event was “held” until the update event for account 8006 was inserted. Even though the updates for account 8004 and 8005 occur outside of account 8003’s update event window at 09:00:45 they were published to separate partitions.</p><p>It appears that ksqlDBs window processing is applied to the same partition. Since account 8006 is published to the same Partition that account 8003 resides in then that essentially unsticks account 8003’s update event.</p><p>A final event is inserted for an update to account 8002 at 09:03:30. This event occurs well after the account 8006 update.</p><pre>INSERT INTO account_info (accountId, operation, productCode, balance, changeDateTime) <br>VALUES (&#39;8002&#39;, &#39;update&#39;, &#39;12&#39;, 1500.00, &#39;2023-08-20T09:03:30&#39;);</pre><p>The result is the previous updates for accounts 8004 and 8005 are unstuck given they are on the same partition as the account 8002 update.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bsGdHw_UUvyjWBPG5eCfpA.png" /></figure><p>This sequence illustrates two key aspects stream-stream FULL OUTER joins in relation to non-joined events:</p><ul><li>Non-joined events are only published after the window has completed, as expected by including the GRACE period and preventing eagerly published events (2).</li><li>Non-joined events are only published when subsequent events are published into their respective streams on the same partition. This is due to our use of event-time semantics (3) (4) where ksqlDB relies on the timestamps within the events to determine the window join behaviour and so events won’t be automatically published by ksqlDB. If there are no other events for some time then the non-joined event won’t be published into the joined stream for that time.</li></ul><h3>Materialised Views</h3><p>In the second part of this article series we’ll explore an alternative approach that leverages materialised views in creating a stream with the targeted business events. Hopefully leveraging a materialised views push capability we can have non-joined events published without other events needing to unstick them. We’ll add in support for joining some data from other sources for bonus points.</p><p>References</p><p>(1) <a href="https://docs.ksqldb.io/en/latest/developer-guide/joins/join-streams-and-tables/#:~:text=Semantics%20of%20Stream%2DStream%20Joins,-The%20semantics%20of&amp;text=All%20records%20have%20the%20same,grace%20period%20is%205%20seconds.">Stream Joins, ksqlDB Documentation</a></p><p>(2) <a href="https://www.confluent.io/blog/ksqldb-0-23-1-features-updates/">ksqlDB Grace Period Announcement</a></p><p>(3) <a href="https://docs.ksqldb.io/en/latest/concepts/time-and-windows-in-ksqldb-queries/">ksqlDB Time Semantics</a></p><p>(4) <a href="https://docs.ksqldb.io/en/latest/reference/sql/time/">Time operations</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ebf30b38b75" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Joining multiple materialised views using KSQLDB]]></title>
            <link>https://tonykambo.medium.com/joining-multiple-materialised-views-using-ksqldb-55c9def9de3a?source=rss-869f12e14412------2</link>
            <guid isPermaLink="false">https://medium.com/p/55c9def9de3a</guid>
            <category><![CDATA[merge]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[materialised-view]]></category>
            <category><![CDATA[ksqldb]]></category>
            <category><![CDATA[join]]></category>
            <dc:creator><![CDATA[Tony Kambourakis]]></dc:creator>
            <pubDate>Fri, 16 Dec 2022 10:55:16 GMT</pubDate>
            <atom:updated>2022-12-16T10:55:16.143Z</atom:updated>
            <content:encoded><![CDATA[<p>The example scenario is a retail banking loan solution where a customer initially undertakes a needs analysis interview via an online web form based application that identifies the right product for the customer.</p><p>The customer is then provided a quote for the loan including rates and fees with which they may choose to tailor the loan characteristics.</p><p>Finally in accepting the quote the customer submits a loan application that will trigger the accounts origination process. These three phases of the customer enquiry are handled by separate bounded contexts; Needs Analysis, Quoting and Loan Application. A stream from each bounded context feeds into another bounded context that oversees the customer’s loan enquiry, the Enquiry bounded context.</p><p>There are two serverless functions, one providing the means to create the customer enquiry and the other to retrieve the details of the customer’s enquiry. These functions integrate directly with KSQLDB and provide an API for a front end web view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QErH8nESsDmBRjAZSZpYUQ.png" /><figcaption>Materialised View Multiple Joins</figcaption></figure><p>In the next example we’ll establish a materialised view (2) from a base materialised view and join two other materialised views of which one is built from multiple, merged streams.</p><h4>Setting up the tables and streams</h4><p>First create the streams from each of the Needs Analysis, Quoting and Loan Application bounded contexts. These will drive the resume point and status of the enquiry. The resume point tells the consuming web view where the customer has reached in the enquiry journey. This would allow the web view to then engage with the right bounded context if the customer stops and then later resumes their enquiry.</p><pre>CREATE STREAM NeedsAnalysisInterviewStarted (enquiryId VARCHAR KEY, customerId VARCHAR) WITH (kafka_topic=&#39;NeedsAnalysisInteriewStartedTopic&#39;, value_format=&#39;json&#39;, partitions=3);<br>CREATE STREAM QuoteIssued (enquiryId VARCHAR KEY, customerId VARCHAR) WITH (kafka_topic=&#39;QuoteIssuedTopic&#39;, value_format=&#39;JSON&#39;, partitions=3);<br>CREATE STREAM LendingApplicationInterviewStarted (enquiryId VARCHAR KEY, customerId VARCHAR) WITH (kafka_topic=&#39;LendingApplicationInterviewStartedTopic&#39;, value_format=&#39;JSON&#39;, partitions=3);<br>CREATE STREAM LendingApplicationInterviewSubmitted(enquiryId VARCHAR KEY, customerId VARCHAR) WITH (kafka_topic=&#39;LendingApplicationInterviewSubmittedTopic&#39;, value_format=&#39;JSON&#39;, partitions=3);</pre><p>Create the ResumePoint stream to capture the changes to the enquiry resume point.</p><pre>CREATE STREAM ResumePoint (enquiryId VARCHAR KEY, resumePoint VARCHAR) with (kafka_topic=&#39;ResumePointTopic&#39;, value_format=&#39;JSON&#39;,partitions=3);</pre><p>Merge the Needs Analysis, Quote and Loan Application bounded context streams into the Resume Point stream. These are continuous running queries deployed into KSQLDB.</p><pre>INSERT INTO ResumePoint select enquiryId, &#39;INTERVIEW&#39; as resumePoint FROM NeedsAnalysisInteriewStarted;<br>INSERT INTO ResumePoint select enquiryId, &#39;QUOTE&#39; as resumePoint FROM QuoteIssued;<br>INSERT INTO ResumePoint select enquiryId, &#39;LOANAPPLY&#39; as resumePoint FROM LendingApplicationInterviewStarted;</pre><p>The ResumePointMV materialised view table utilises the LATEST_BY_OFFSET aggregation function to return the latest resume point value for an enquiry. This will be joined with the main customer enquiry materialised view table.</p><pre>CREATE TABLE ResumePointMV as <br> select enquiryId, <br>   LATEST_BY_OFFSET(resumepoint) as latestResumePoint <br> from ResumePoint <br> group by enquiryId <br> emit changes;</pre><p>The CustomerEnquiryStatusUpdated stream holds the changes to the enquiry status.</p><pre>CREATE STREAM CustomerEnquiryStatusUpdated (enquiryId VARCHAR KEY, enquiryStatus VARCHAR) <br>WITH (kafka_topic=&#39;CustomerEnquiryStatusUpdatedTopic&#39;, value_format=&#39;JSON&#39;, partitions=3);</pre><p>The CustomerEnquiryStatusUpdatedMV materialised view table utilises the LATEST_BY_OFFSET aggregation function to return the latest status of the enquiry.</p><pre>CREATE TABLE CustomerEnquiryStatusUpdatedMV as <br> select enquiryId, <br>   LATEST_BY_OFFSET(enquiryStatus) AS latestEnquiryStatus <br> FROM CustomerEnquiryStatusUpdated <br> GROUP BY enquiryId <br> emit changes;</pre><p>The CustomerEnquiryCreated stream holds the event that represents the creation of an enquiry. The Create Customer Enquiry Function is responsible for generating a unique enquiry identifier that will be passed into the event. There is only ever one entry for an enquiryId however a customer may have multiple enquiries.</p><pre>CREATE STREAM CustomerEnquiryCreated (enquiryId VARCHAR KEY, customerId VARCHAR, enquiryType VARCHAR, enquiryChannel VARCHAR) <br>WITH (kafka_topic=&#39;CustomerEnquiryCreatedTopic&#39;, value_format=&#39;JSON&#39;, partitions=3);</pre><p>The CustomerEnquiryBaseMV materialised view table utilises the LATEST_BY_OFFSET aggregation function across the customerId, enquiryType and enquiryChannel columns.</p><pre>CREATE TABLE CustomerEnquiryBaseMV AS<br>  SELECT enquiryId, <br>  LATEST_BY_OFFSET(customerId) AS customerId, <br>  LATEST_BY_OFFSET(enquiryType) AS enquiryType, <br>  LATEST_BY_OFFSET(enquiryChannel) AS enquiryChannel<br>  FROM CustomerEnquiryCreated<br>  GROUP BY enquiryId<br>EMIT CHANGES;</pre><p>The CustomerEnquiryMV materialised view (table) joins the resumePoint from the ResumePointMV materialised view (table) and the enquiryStatus from the CustomerEnquiryStatusUpdatedMV materialised view (table).</p><pre>CREATE TABLE CustomerEnquiryMV AS<br> SELECT c.enquiryId AS enquiryId, c.customerId, c.enquiryType, c.enquiryChannel, r.latestResumePoint, s.latestEnquiryStatus<br>  FROM CustomerEnquiryBaseMV c<br>  LEFT JOIN ResumePointMV r ON c.enquiryId = r.enquiryId<br>  LEFT JOIN CustomerEnquiryStatusUpdatedMV s ON c.enquiryId = s.enquiryId<br>EMIT CHANGES;</pre><p>Establish running query that will merge the CustomerEnquiryCreated stream into the CustomerEnquiryStatusUpdated stream, however the status is set to ACTIVE directly just on an event for that enquiryId being added to the CustomerEnquiryCreated stream.</p><pre>INSERT INTO CustomerEnquiryStatusUpdated <br> select enquiryId, &#39;ACTIVE&#39; AS enquiryStatus <br>FROM CustomerEnquiryCreated;</pre><p>Similarly the LendingApplicationInterviewSubmitted stream is merged into the CustomerEnquiryStatusUpdated stream. The status is set to COMPLETED if an event for that enquiryId is published to the LendingApplicationInterviewSubmitted stream</p><pre>INSERT INTO CustomerEnquiryStatusUpdated <br> select enquiryId, &#39;COMPLETED&#39; AS enquiryStatus <br>FROM LendingApplicationInterviewSubmitted;</pre><p>Establish running query that will merge in the HOME resume point when an enquiry is created.</p><pre>INSERT INTO ResumePoint <br> select enquiryId, &#39;HOME&#39; AS resumePoint <br>FROM CustomerEnquiryCreated;</pre><h4>Running the example</h4><p>Create a new customer enquiry.</p><pre>INSERT INTO CustomerEnquiryCreated (enquiryId, customerId, enquiryType, enquiryChannel) <br>VALUES (&#39;33050&#39;,&#39;1001&#39;,&#39;LOAN&#39;,&#39;ONLINEWEB&#39;);</pre><p>Confirm the enquiry has been added.</p><pre>SELECT * FROM CustomerEnquiryMV;<br><br>+----------+-----------+------------+--------------+------------------+--------------------+<br>|ENQUIRYID |CUSTOMERID |ENQUIRYTYPE |ENQUIRYCHANNEL|LATESTRESUMEPOINT |LATESTENQUIRYSTATUS |<br>+----------+-----------+------------+--------------+------------------+--------------------+<br>|33050     |1001       |LOAN        |ONLINEWEB     |HOME              |ACTIVE              |</pre><p>Note that the LATESTRESUMEPOINT column is set to HOME and the LATESTENQUIRYSTATUS is set to ACTIVE due to the multiple stream joins for the materialised view. The CustomerEnquiryCreated stream join resulted in the initial status set to ACTIVE and also the initial resume point being set to HOME.</p><p>The customer begins with the Needs Analysis phase and the Needs Analysis bounded context publishes an event to the NeedsAnalysisInterviewStarted stream to indicate the interview started. <br>After the digital interview has been started the started event will drive the resume point to INTERVIEW.</p><pre>INSERT INTO NeedsAnalysisInterviewStarted (enquiryId, customerid) <br>VALUES (&#39;33050&#39;,&#39;1001&#39;);</pre><p>Confirm the LATESTRESUMEPOINT is set to INTERVIEW.</p><pre>SELECT * FROM CustomerEnquiryMV;<br><br>+----------+-----------+------------+--------------+------------------+--------------------+<br>|ENQUIRYID |CUSTOMERID |ENQUIRYTYPE |ENQUIRYCHANNEL|LATESTRESUMEPOINT |LATESTENQUIRYSTATUS |<br>+----------+-----------+------------+--------------+------------------+--------------------+<br>|33050     |1001       |LOAN        |ONLINEWEB     |INTERVIEW         |ACTIVE              |</pre><p>Now the customer enters the quote phase.</p><pre>INSERT INTO QuoteIssued (enquiryId, customerid) VALUES (&#39;33050&#39;,&#39;1001&#39;);</pre><p>Confirm the LATESTRESUMEPOINT is set to QUOTE.</p><pre>SELECT * FROM CustomerEnquiryMV;<br><br>+----------+-----------+------------+--------------+-----------------+--------------------+<br>|ENQUIRYID |CUSTOMERID |ENQUIRYTYPE |ENQUIRYCHANNEL|LATESTRESUMEPOINT|LATESTENQUIRYSTATUS |<br>+----------+-----------+------------+--------------+-----------------+--------------------+<br>|33050     |1001       |LOAN        |ONLINEWEB     |QUOTE            |ACTIVE              |<br><br></pre><p>Finally the customer enters the loan application phase.</p><pre>INSERT INTO LendingApplicationInterviewStarted (enquiryId, customerid) <br>VALUES (&#39;33050&#39;,&#39;1001&#39;);</pre><p>Confirm the LATESTRESUMEPOINT is set to QUOTE.</p><pre>SELECT * FROM CustomerEnquiryMV;<br><br>+----------+----------+------------+--------------+------------------+--------------------+<br>|ENQUIRYID |CUSTOMERID|ENQUIRYTYPE |ENQUIRYCHANNEL|LATESTRESUMEPOINT |LATESTENQUIRYSTATUS |<br>+----------+----------+------------+--------------+------------------+--------------------+<br>|33050     |1001      |LOAN        |ONLINEWEB     |QUOTE             |ACTIVE              |<br><br></pre><p>If you query is run immediately after the insert the LATESTRESUMEPOINT may still show as QUOTE as above. This is due to the eventual consistency model underpinning table to table joins in KSQLDB (1).</p><p>Running the query again after a couple of seconds returns the LATESTRESUMEPOINT set to LOANAPPLY.</p><pre>SELECT * FROM CustomerEnquiryMV;<br><br>+----------+-----------+------------+--------------+------------------+--------------------+<br>|ENQUIRYID |CUSTOMERID |ENQUIRYTYPE |ENQUIRYCHANNEL|LATESTRESUMEPOINT |LATESTENQUIRYSTATUS |<br>+----------+-----------+------------+--------------+------------------+--------------------+<br>|33050     |1001       |LOAN        |ONLINEWEB     |LOANAPPLY         |ACTIVE              |</pre><p>Finally when the loan application has completed the enquiry status will be set to COMPLETED.</p><pre>INSERT INTO LendingApplicationInterviewSubmitted (enquiryId, customerid) <br>VALUES (&#39;33050&#39;,&#39;1001&#39;);</pre><p>Confirm the LATESTENQUIRYSTATUS is set to COMPLETED.</p><pre>SELECT * FROM CustomerEnquiryMV;<br><br>+----------+-----------+------------+----------------+-----------------+--------------------+<br>|ENQUIRYID |CUSTOMERID |ENQUIRYTYPE |ENQUIRYCHANNEL  |LATESTRESUMEPOINT|LATESTENQUIRYSTATUS |<br>+----------+-----------+------------+----------------+-----------------+--------------------+<br>|33050     |1001       |LOAN        |ONLINEWEB       |LOANAPPLY        |COMPLETED           |<br><br></pre><h3>References</h3><ol><li><a href="https://docs.ksqldb.io/en/latest/developer-guide/joins/join-streams-and-tables/">Joining collections</a>, ksqlDB Documentation, Confluent</li><li><a href="https://docs.ksqldb.io/en/latest/tutorials/materialized/?_ga=2.184466278.1136703206.1671174062-1059994463.1670188237">Materialised cache</a>, ksqlDB Documentation, Confluent</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55c9def9de3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using aggregation functions in KSQLDB materialised view]]></title>
            <link>https://tonykambo.medium.com/using-aggregation-functions-in-ksqldb-materialised-view-8e4f0dd9d31a?source=rss-869f12e14412------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e4f0dd9d31a</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[events]]></category>
            <category><![CDATA[event-sourcing]]></category>
            <category><![CDATA[aggregation]]></category>
            <category><![CDATA[ksqldb]]></category>
            <dc:creator><![CDATA[Tony Kambourakis]]></dc:creator>
            <pubDate>Fri, 16 Dec 2022 10:29:42 GMT</pubDate>
            <atom:updated>2022-12-16T10:54:07.738Z</atom:updated>
            <content:encoded><![CDATA[<p>An event stream contains changes over time, like an accounting journal — individual events represent a recorded change. For example, a customer granting consent for their data to be shared as with Open Banking. A customer can choose to give consent for sharing their data by providing consent to specific data sets.</p><p>In this example we’ll use two data sets or scopes; the customer’s list of accounts (AccountList) and the customers profile information (CustomerProfile). The customer can either grant or decline consent at any time. A customer may choose to initially grant consent but then decline consent at later time. Whilst the latest customer consent selection could be stored as a single value in a database the value would typically be overridden with each change the customer makes, losing the historical sequence of changes. By using a stream the history of consent changes is captured and may be used to derive other perspectives and insights.</p><p>To determine the final state of a customer’s consent for a scope a materialised view (1) can be created from the stream. A materialised view can be created as a table in KSQLDB that utilises an aggregation function that may be applied to an attribute (2). A scalar function can be used to perform a calculation across the values from each event. In this example, the desired outcome is to determine the final or latest state of the customer’s consent for a specific scope. This can be determined using the LATEST_BY_OFFSET aggregation function. It returns the latest value of the attribute (column) in the underlying stream.</p><p>First, create the consent stream:</p><pre>// Instruct KSQLDB to begin all queries from the earliest point in the topic.<br><br>SET &#39;auto.offset.reset&#39; = &#39;earliest&#39;;<br><br>// Create the stream<br><br>create stream DataSharingConsentStream (customerId STRING KEY, scope STRING KEY, consent STRING) WITH (kafka_topic=&#39;DataSharingConsentTopic&#39;, key_format=&#39;DELIMITED&#39;, partitions=1, value_format=&#39;JSON&#39;);</pre><p>Add sample values to the stream that includes updates from multiple customers and multiple updates from an individual customer.</p><pre>insert into DataSharingConsentStream (customerId, scope, consent) values (&#39;1001&#39;,&#39;CustomerProfile&#39;,&#39;GRANTED&#39;);<br>insert into DataSharingConsentStream (customerId, scope, consent) values (&#39;1001&#39;,&#39;AccountList&#39;,&#39;GRANTED&#39;);<br>insert into DataSharingConsentStream (customerId, scope, consent) values (&#39;1001&#39;,&#39;AccountList&#39;,&#39;DECLINED&#39;);<br>insert into DataSharingConsentStream (customerId, scope, consent) values (&#39;1002&#39;,&#39;CustomerProfile&#39;,&#39;GRANTED&#39;);<br>insert into DataSharingConsentStream (customerId, scope, consent) values (&#39;1003&#39;,&#39;CustomerProfile&#39;,&#39;GRANTED&#39;);<br>insert into DataSharingConsentStream (customerId, scope, consent) values (&#39;1003&#39;,&#39;AccountList&#39;,&#39;DECLINED&#39;);<br>insert into DataSharingConsentStream (customerId, scope, consent) values (&#39;1003&#39;,&#39;AccountList&#39;,&#39;GRANTED&#39;);</pre><p>Confirm the data has been added by running the following query. The query returns each change the customer has made to a scope’s consent. Customer 1001 initially granted consent to AccountList but then declined it later.</p><pre>SET CLI COLUMN-WIDTH 20;<br><br>ksql&gt; select * from DataSharingConsentStream;<br>+-------------------------+-------------------------+-------------------------+<br>|CUSTOMERID               |SCOPE                    |CONSENT                  |<br>+-------------------------+-------------------------+-------------------------+<br>|1001                     |CustomerProfile          |GRANTED                  |<br>|1001                     |AccountList              |GRANTED                  |<br>|1001                     |AccountList              |DECLINED                 |<br>|1002                     |CustomerProfile          |GRANTED                  |<br>|1003                     |CustomerProfile          |GRANTED                  |<br>|1003                     |AccountList              |DECLINED                 |<br>|1003                     |AccountList              |GRANTED                  |</pre><p>Create the materialised view that will provide the latest consent for each customers’ scope. The “LATEST_BY_OFFSET” aggregation function will result in only the latest consent to be returned for the customers’ scope.</p><pre>create table DataSharingConsentMV as <br> select customerId, scope, <br>   LATEST_BY_OFFSET(consent) as latestConsent <br> FROM DataSharingConsentStream <br> group by customerId, scope <br> emit changes;</pre><p>Run a query on the materialised view to show the consent for all customers. Only the latest consent for each customer’s scope is returned.</p><pre>select * from DataSharingConsentMV;<br>+-------------------------+-------------------------+-------------------------+<br>|CUSTOMERID               |SCOPE                    |LATESTCONSENT            |<br>+-------------------------+-------------------------+-------------------------+<br>|1001                     |AccountList              |DECLINED                 |<br>|1001                     |CustomerProfile          |GRANTED                  |<br>|1002                     |CustomerProfile          |GRANTED                  |<br>|1003                     |AccountList              |GRANTED                  |<br>|1003                     |CustomerProfile          |GRANTED                  |</pre><p>Run a query for a specific customer’s scope.</p><pre>select * from DataSharingConsentMV where customerId=&#39;1001&#39; and scope=&#39;AccountList&#39;;<br>+-------------------------+-------------------------+-------------------------+<br>|CUSTOMERID               |SCOPE                    |LATESTCONSENT            |<br>+-------------------------+-------------------------+-------------------------+<br>|1001                     |AccountList              |DECLINED                 |</pre><h3>References</h3><ol><li><a href="https://docs.ksqldb.io/en/latest/tutorials/materialized/?_ga=2.184466278.1136703206.1671174062-1059994463.1670188237">Materialised cache</a>, ksqlDB Documentation, Confluent</li><li><a href="https://docs.ksqldb.io/en/latest/developer-guide/ksqldb-reference/aggregate-functions/">Aggregation functions</a>, ksqlDB Documentation, Confluent</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e4f0dd9d31a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Browser integration with WebSockets, Kafka and KSQLDB]]></title>
            <link>https://tonykambo.medium.com/browser-integration-with-websockets-kafka-and-ksqldb-ff2e10f3c001?source=rss-869f12e14412------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff2e10f3c001</guid>
            <category><![CDATA[ksqldb]]></category>
            <category><![CDATA[integration]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[signalr]]></category>
            <category><![CDATA[websocket]]></category>
            <dc:creator><![CDATA[Tony Kambourakis]]></dc:creator>
            <pubDate>Mon, 12 Dec 2022 11:15:21 GMT</pubDate>
            <atom:updated>2022-12-12T11:24:58.821Z</atom:updated>
            <content:encoded><![CDATA[<p>Tony Kambourakis, Principal Architect, IBM<br>Jamin Adey, Principal Architect — Digital, Fidelity Life Assurance<br>Tarun Sharma, Azure Enterprise Solutions Architect, IBM</p><h3>Overview</h3><p>A popular browser integration style used in developing browser-based business applications is synchronous HTTP-based APIs. The browser application client code, be it JavaScript or TypeScript, either requests data or submits data to one of various endpoints, typically mapped to a server-side application, a Backend For Frontend (BFF) and a microservice. In turn the microservice may retrieve data from or commit data to a database or publish an event/message to an event/messaging system such as IBM MQ, AWS SQS or Apache Kafka.</p><figure><img alt="Typical HTTP-based API integration with browser invoking Backend for Front end services via an API Gateway. The BFFs integrate with databases and/or messaging systems." src="https://cdn-images-1.medium.com/max/1024/1*TYpnpQTP4Ju8Vix_42bHEA.png" /><figcaption>HTTP-based API integration</figcaption></figure><p>Alternatively, a chat style application tends to use an asynchronous form of integration such as WebSocket. These allow for both client and server to initiate the transmission of data from either end, without the need for a response. Similarly, dashboard style applications can utilise a WebSocket to receive a continuous stream of data to update their views.</p><p>In this article we look to explore a solution in combining WebSockets with Kafka for a business application that would typically have used an HTTP API based integration style. This provides the browser application client with a single integration style to both submit and receive data, without the need for polling for updates from the server-side, which does not only waste resources, but introduces increased latency; a) by having to wait for next poll frequency to occur before obtaining the result, which may have already been processed b) by not having the added overhead of recreating HTTPS handshake, and requiring the full set of HTTP headers to be sent with each request.</p><p>We’ll use Azure SignalR and Confluent Cloud (an Apache Kafka Platform-as-a-Service provider) with KSQLDB as examples.</p><h3>WebSocket Connections</h3><p>The solution comprises the browser application client utilising the SignalR SDK to establish a WebSocket connection with the Azure SignalR service to send and receive data. The data can be structured in the form of commands or events. In the example below, the browser application client follows a micro-frontend (MFE) design with separate bounded contexts provided by an Accounts MFE and a Transactions MFE. Each MFE has its own WebSocket connection to its associated SignalR Hub, one for each bounded context.</p><p>The goal is for each MFE to run independently along with its own backing services. The only thing that should be shared between the MFEs when moving from one to another (usually within a parent hosting web app) is some kind of unique session/object identifier passed at the UI layer (often in the URL which forms an agreed contract between MFEs). This means the backing services of each MFE (i.e. within its bounded context) requires its own up-to-date knowledge of the context, rather than having shared state (either frontend e.g. redux or backend) across them which would tightly couple them and remove the benefits that modular, independently deployable Micro-frontend and Microservices patterns bring. Using a technology such as Kafka, especially leveraging Confluent’s KSQLDB streaming capability, highly simplifies publishing and subscribing to events across bounded contexts to enable loosely-coupled choreography patterns.</p><p>Azure SignalR Hubs are there to group a set of common messages, much like a Topic in Apache Kafka. With MFEs scoped to a bounded context, and with their own SignalR hub, then any messages will be guaranteed to only be part of that bounded context, which a) ensures encapsulation b) introduces granular auth control as connecting to a hub for a particular MFE can now be authorised, with only permitted users to be able to use the particular MFE’s services (5).</p><p>The Accounts MFE presents a list of the customer’s accounts with their respective balances that it retrieves using a “RetrieveAccountsCmd” command. The Accounts Azure Function receives the “RetrieveAccountsCmd” command and performs a pull query against the associated Accounts KSQLDB materialised view to return the accounts for that customer. The Accounts Function sends the account list to the browser application client as an independent event — “AccountListUpdatedEvent”. Any updates to the account summary list will trigger the Account Function, through the KSQLDB materialised view’s underlying backed topic.</p><p>The triggered Account Function would then send the Account List Updated Event with the revised account list to the client.</p><figure><img alt="WebSocket based integration with a browser connecting to Azure Functions via Azure SignalR. The Functions integrate to Confluent Cloud and KSQLDB to publish and retrieve events." src="https://cdn-images-1.medium.com/max/1024/1*JmehYyIH3OP-Dv21eQMTGw.png" /><figcaption>WebSocket-based integration with Azure SignalR</figcaption></figure><p>When a browser client connects to the Azure SignalR service it is assigned a unique session identifier. The downstream system receiving events sent to SignalR may send messages to clients using either the session identifier, authenticated user identifier or a group identifier. To avoid polluting the Kafka topics and streams with any SignalR specific identifiers (session identifier), the customer identifier is used.</p><p>When the Account Function is trigged by Account List Updated events from Kafka, it receives events for all customers. The function will send the event to the appropriate browser instance (via SignalR socket session) by addressing it to the customer identifier.</p><p>For Kafka, Azure functions uses the built-in integration capability “Kafka Trigger” to listen to any changes in the underlying Kafka topic and receive all the new messages or events published in the topic. Similarly, the Azure function uses the built-in integration capability “Output binding” for publishing a message or event to a topic (3). Only configuration (no coding) in terms of broker details, topic name, protocol etc. is required to publish or subscribe to the Kafka topic. An alternative approach is to use the KSQLDB SDK to publish to a stream.</p><h3>Concurrent Browser Sessions</h3><p>A key benefit of using WebSocket connections is the ability to send updates to multiple browsers concurrently. This avoids having multiple browsers send polling requests into your services to check if there is new or changed data. However, there may be a business requirement to restrict access by a user from multiple browsers/tabs concurrently.</p><p>The Azure SignalR service offers a publish/subscribe mechanism for easily broadcasting messages to multiple clients using Groups <strong>(1)</strong>. When a connection is established with Azure SignalR a client is given a Connection ID. A client may be subscribed to the group by adding its Connection ID to the group (6).</p><p>Expanding on the accounts example the following scenario includes an already established connection from a browser (Browser Instance #1) and the subsequent connection of a second browser instance by the same user (Browser Instance #2). In this case the requirement is to allow only a single browser instance to interact with the user’s data at any one time. A new browser instance will be able to connect, any previously connected browser instance will be disconnected.</p><figure><img alt="WebSocket based integration scenario with two browsers connected via SignalR. Browser one is already connected and browser two subsequently connections and the system forces the first browser to disconnect." src="https://cdn-images-1.medium.com/max/1024/1*wG5F3TkeLgX6pxHnOhYZfQ.png" /><figcaption>Concurrent browser connections</figcaption></figure><p>The example begins after the user has authenticated. In our application, we need to support two scenarios: customer self-service and staff assisting a customer. This means that there will be two possible identity types who have authenticated, the customer and a staff member.</p><p>When the customer logs in, their customer ID will be minted as a user identifier claim in the JWT. For a staff member, only the staff ID will be minted as a user identifier in the JWT and not the customer ID, as a staff member can perform assisted actions for any of their given customers. For customers therefore, the customer ID in the JWT can be trusted to perform authorisation that any actions are scoped to that customer’s business and what they’re permitted to do with it. For staff, the customer ID will need to be passed as a parameter, and therefore, the operations invoked will require ensuring that customer is indeed one the staff member is authorised to perform specific actions for.</p><p>The browser has received a JWT containing the authenticated user identifier. Browser Instance #1 has already connected and has been interacting with the system. The user launches Browser Instance #2 and authenticates.</p><ol><li>The Accounts MFE sends a connection request to the Socket Negotiate Azure Function.</li><li>The Socket Negotiate function initiates a connection with the Azure SignalR service that returns a connection URL and Access Token that is returned to the browser.</li><li>The Accounts MFE establishes a connection with the Azure SignalR Account Hub, using the connection URL and Access Token.</li><li>The Accounts MFE sends the AddCustomerSessionMappingCmd<strong> </strong>command to the Account Hub. The micro UI starts a timeout timer that it will use to confirm the system has registered its new connection identifier by it receiving a SessionMappingUpdated<strong> </strong>message.</li><li>The Account Hub forwards the AddCustomerSessionMappingCmd<strong> </strong>to the Update Customer Session Mapping<strong> </strong>function.</li><li>The Update Customer Session Mapping function adds Browser Instance #2’s Connection<strong> </strong>ID to the SignalR<strong> </strong>group that has the group name set to the user identifier (if the group does not exist, a new group is created). The function utilises the Azure SignalR SDK that internally pushes the group update to the SignalR<strong> </strong>service.</li><li>The Update Customer Session Mapping function broadcasts the RemoveDuplicateSession<strong> </strong>message to the group, excluding the Connection<strong> </strong>ID (2) it just added for the Browser Instance #2. Any browser connections within the group will receive this message and close their connection to the SignalR<strong> </strong>service, optionally informing the user that another session has been established and restricting them from proceeding.</li><li>(a) The Browser Instance #1 MFE receives the RemoveDuplicateSession<strong> </strong>message and closes the SignalR connection. It can present to the user a message that another session has been established, restricting the user from continuing with the application. (b) The Update Customer Session Mapping<strong> </strong>function broadcasts the SessionMappingUpdated<strong> </strong>message to the group that now only includes the Browser Instance #2.</li><li>The Browser Instance #2 Accounts MFE receives the SessionMappingUpdated<strong> </strong>message and stops the timeout timer, confirming its connection has been registered.</li><li>Accounts MFE sends RetrieveAccountsCmd<strong> </strong>command to Account Hub.</li><li>Accounts Hub forwards RetrieveAccountsCmd<strong> </strong>to the Accounts<strong> </strong>Aure function that in turn reads from the Accounts KSQLDB Materialised View.</li><li>The Accounts function sends the Account List Updated event to the Account Hub, addressed to the group name.</li><li>The Account Hub forwards the Account List Updated event to the Accounts MFE.</li></ol><p>By setting the group name equal to the user identifier the various functions can source data from Kafka/KSQLDB using business identifiers rather than SignalR specific identifiers such as the Connection ID. In the step where the Accounts function is triggered by an update to the Account List, the KSQLDB/Kafka topic will contain the user identifier that the change is related to. The Accounts function will then use that user identifier as the group name it sends the Account List Updated event without needing to know the browser’s SignalR connection identifier.</p><h3>Handling Disconnections</h3><p>If the web socket connection is momentarily broken due to a loss of network connection SignalR will attempt to reconnect and invoke the “reconnecting” connection lifetime event. This could trigger the browser application client to provide an alert to the user and block them from continuing to make updates via the UI.</p><p>Upon reconnection SignalR assigns the browser client a new Connection ID, replacing the previous Connection ID in the group with the new one. The replacement of the Connection ID happens transparently to the browser application client code and as such there is no need to send the AddCustomerSessionMappingCmd command.</p><h3>Error Handling and Correlation</h3><p>Since this type of solution relies on asynchronous integration (Fire &amp; Forget or Notifications), error handling needs a different approach. In an API-based synchronous integration, the calling thread would have the status of the request success or failure, it is easy to perform error handling processing. In an asynchronous integration, the publication of a message or event may have a consequence unknown to the publisher, there is a need for some mechanism to communicate any downstream error (if and when happen) to the publisher.</p><p>For KsqlDB, “KSQL_Processing_Log” provides details of all the stream processing activities performed on Topic, Stream, and Tables including any error such as schema validation errors (4). The data in this log can be used to identify the error that occurred by transforming the error information appropriately and storing it in another topic which then can trigger an error handling function with the details and cause of the error. The error handling Azure function then can communicate to the particular UI Client via the SignalR service.</p><p>There may be in some cases a need for a correlation of the error or (even a successful response) so that the error can be stitched (correlated) to the original message or event to be played back to the corresponding UI Client. In scenarios where a retry publication request is made this “correlationID” can be used to ignore all other responses however this warrants the error or success response contains the “correlationID” which is the unique MessageID of the request.</p><h3>References</h3><ol><li><a href="https://learn.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/working-with-groups">Working with Groups in SignalR</a>, Guide to the API, Microsoft</li><li><a href="https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.signalr.hubclientsextensions.groupexcept?view=aspnetcore-7.0">HubClientsExtensions.GroupExcept</a> Method, Microsoft.AspNetCore.SignalR, Microsoft</li><li><a href="https://learn.microsoft.com/en-us/azure/azure-functions/functions-triggers-bindings">Azure Functions triggers and bindings concepts</a>, Microsoft</li><li><a href="https://docs.ksqldb.io/en/latest/reference/processing-log/">KSQL Process Log</a>, KSQLDB, Confluent</li><li><a href="https://learn.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/hubs-api-guide-javascript-client#connectionlifetime">ASP.NET SignalR Hubs API Guide — JavaScript Client</a>, Microsoft</li><li><a href="https://consultwithgriff.com/signalr-connection-ids/">Managing SignalR ConnectionIds (or why you shouldn’t)</a>, Kevin W. Griffin</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff2e10f3c001" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Approach and challenges of Open Banking APIs with CQRS and Core Banking Mainframe]]></title>
            <link>https://tonykambo.medium.com/approach-and-challenges-of-open-banking-apis-with-cqrs-and-core-banking-mainframe-5d7ace3dbca2?source=rss-869f12e14412------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d7ace3dbca2</guid>
            <category><![CDATA[cqrs]]></category>
            <category><![CDATA[cdc]]></category>
            <category><![CDATA[events]]></category>
            <category><![CDATA[banking]]></category>
            <category><![CDATA[mainframe]]></category>
            <dc:creator><![CDATA[Tony Kambourakis]]></dc:creator>
            <pubDate>Thu, 30 Jun 2022 09:16:36 GMT</pubDate>
            <atom:updated>2022-06-30T09:16:36.587Z</atom:updated>
            <content:encoded><![CDATA[<p>Tony Kambourakis, <em>Principal Architect, IBM<br></em>Sangeetha Sridharan, <em>Information Architect, IBM<br>Simon Hudson, Senior Managing Consultant, IBM</em></p><h3>Overview</h3><p>In supporting <a href="https://www.ausbanking.org.au/priorities/open-banking/">Open Banking</a> an organisation may wish to make data managed by their core banking system (typically running on a mainframe) and customer Master Data Management (MDM) available for retrieval via the <a href="https://consumerdatastandardsaustralia.github.io/standards/#introduction">Open Banking API</a>. They may have an existing API that retrieves this data directly from these systems for their Internet Banking application. In some cases, the banking organisation may have accumulated multiple brands that result in many core systems resulting in multiple source systems.</p><p>One approach is to establish a capability to extract the data from a banking organisation’s core systems into a separate, read-optimised data store that could be used to expose data to their Open Banking API and Internet Banking application.</p><p>The goals include:</p><ol><li>Reducing on-going mainframe costs by minimising the direct consumption of mainframe services from Internet Banking and Open Banking applications.</li><li>Consolidate data from various core systems accumulated through years of brand acquisitions into a single data layer to retrieve from.</li></ol><p>In this article we look to explore a solution, highlighting some of the key challenges along the way.</p><h3>Solution</h3><p>The solution comprises a read-optimised data store to retain a copy of the data that includes account, transaction and customer information. The data store receives the feed of data from source systems via Kafka. CDC is used to detect and publish changes to the source system databases and publish the changes as events into Kafka. CDC publishes the events in a raw data format that mirrors the schema of the databases. The data is transformed, via a Stream Processor System, into a canonical format to persist the data in a read-optimised form in the data stores and to drive the publishing of business events that supports an event-driven architecture within the enterprise.</p><p>The data store is divided into separate databases, one for each domain that are accessible via an associated domain microservice. The microservices provide an API that is based on the canonical model and exposes the APIs across external channels and internal applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Mbm4aOthjJn8mw04BRsmw.png" /><figcaption>Architecture Overview</figcaption></figure><h3>Using CDC to publish raw events</h3><p>The underlying event driven architecture of the system establishes a set of business events that are produced and consumed by various systems as part of a choreography of events. The events present business significant occurrences such an account being created (account origination), a customer’s details being updated, a financial transaction occurring and a scheduled payment being created.</p><p>One approach is to have the source systems of these events publish them directly to the event/messaging system. However, this requires the source system to either already support this mechanism or to be modified to publish events. Change Data Capture (CDC) provides a non-intrusive way of detecting the changes within the source system and publish the changes as events.</p><p>This approach leads to the technical challenge where the events published by the CDC system are a direct reflection of the source system’s internal database schema.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4u2KfTpgYfip7j3OVVZKpA.png" /><figcaption>Example Source System Database Schema</figcaption></figure><p>The events published by the CDC system are fine grained and will likely not include the necessary data to build an associated business event. As such, an involved series of transformation and enrichment steps are needed to combine and form the data required in the business event. Some data is spread across multiple tables in the source system database. CDC will publish the changes to each table as separate events.</p><p>To build a single business event multiple raw events would need to be combined requiring a window-based process within the Stream Processing System. That is, when a raw message is received, the Stream Processing System will allow for a certain window of time to receive subsequent events to combine the data into the single business event. In some cases, the changes to the tables do not include all the data that would be required for the business event and so an Intermediate Data Cache will need to be maintained to add the data necessary to complete the business events schema.</p><p>The Intermediate Data Cache is maintained as a replica of the subset of tables required when CDC publishes raw messages to the kafka topics. The enrichment of meaningful business event is performed by combining the source raw message with the data in the Intermediate Data Cache.</p><p>The events were identified where more than one underlying source table gets changed, these events combined the data stream from multiple topics (stream join) and published as events.</p><p>In converting a raw event to an associated business event, the changes applied on the raw table columns are identified as CDC includes the before and after state. Though in some cases it is not possible to identify the raw event as the various combinations of arrival times and content may be too complex. To work around that the events can be grouped by CDC and CDC may perform a back-query to the source system before publishing the raw event in order to enrich the raw event with the required additional column information. This helps avoid ambiguous event creation and reducing the use of the Intermediary Data Cache. There is an impact to performing the back-query against the source system database but the core system processing component is not impacted and so this approach is used sparingly.</p><p>The event schemas are also standardised to make avoid source system specific values. For instance, an active account status could be stored with a value of “O” (representing open) or “A” (for Active) or “1” (true ) in that specific source system. To make this as a system agnostic representation a standardization representation may be introduced. This was achieved using a reference look up, which acts as a conversion mechanism from source specific values to standard values when data being persisted and published. This reference changes from source are periodically updated from the source master data management system.</p><p>Additional areas that will have further challenges include identifying missing data, capturing what cannot be published as a successful event and reprocessing events to keep the data integrity. Some scenarios that may need to be handled include late arriving stream events from source systems, late arriving updates to intermediary cache, missing data in reference lookup, race issue with events occurring at the same time with few seconds/ microseconds difference, batch processing resulting in multiple commits on the same record.</p><h3>Event Granularity</h3><p>The granularity and content of business events are also a challenge with striking the right balance. Course grained events such as Account Created and Account Updated will include a large set of data that reflects various attributes relevant for the event.</p><p>The Account Updated event contains both attributes that have been changed along with attributes that have not been changed. This is to provide the contextual details of the account that have been updated to consumers without requiring the consumer to make a subsequent call to retrieve the details of the account that have not been changed. Conversely a fined grained event will focus on the specific change, in the case of the Account Update finer grained events could include Account Status Updated, Account Fraud Status Updated, Account Pricing Group Updated, Account Balance Updated.</p><p>Whilst the finer grained events are clearer in their change consumers are subscribing to far more events of which the order may be critically important. One approach is to keep the course grained event of Account Updated but include a “change set” attribute that indicates which related data block within the structure has been updated to help the consumer narrow down on the nature of the change that drove the event. The Account Balance event could be a deviation from this approach where the Account Update events are significantly driven by balance changes. For consumers that are not interested in balance changes this adds the burden of filtering out most of these events on the consumer. As such a separate Account Balance event can be defined to avoid this burden.</p><p>The business event is used as both an event that will underpin an event-driven architecture within the enterprise, allowing for both interface and temporal decoupling between systems, and the means to essentially copy the source system data to the read-optimised store.</p><h3>Event Ordering</h3><p>Strict ordering is required at various stages right from CDC, Kafka and the Stream Processing System until the data is persisted to the data store. Identifying the right partition key for each domain and event is a key factor in determining and maintaining the order for publishing events. The audit columns of source tables that include timestamps can be included in the raw events from CDC and may also be used to determine the order of events. This helps to maintain idempotency when the same records are reprocessed at the consumer level. These aspects must be considered by the Stream Processing System to ensure processing and writing to the database is made in strict order of the events.</p><h3>Core System Logic</h3><p>Not all account data can be stored in the read-optimised data store; some required calculations (certain account balances) and therefore the account microservice would make API calls to mainframe whilst other types would be retrieved from data store.</p><p>An example of a calculated field may be <em>available balance</em> on an account. With data such as <em>available balance</em>, there are two reasons not to persist this in the read only database layer:</p><ol><li>consumers need to be 100% confident that the data is accurate at a point in time — eventual consistency may not be enough for consumers of this field</li><li>“available balance” may not be persisted in the core banking DB, often it is derived each time it is needed — therefore the same logic that is used to calculate it in the core would need to be replicated in the Data Services layer</li></ol><p>To solve for this use case, APIs exposed by the Core Banking Platform can be used to augment the data that exists in the read-optimised data store.’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5uc_719f95aTSyYvmr5djQ.jpeg" /><figcaption>Mainframe API Call for Account Balance</figcaption></figure><p>Other use cases for calculated fields that may follow a similar pattern include redraw amounts (min/max), and interest rates on an account.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d7ace3dbca2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>