# The Write Ahead Log > The Write Ahead Log is the engineering journal of Platformatory, a forward deployed engineering firm for data, AI and modernization. It is written by the engineers who build and run these systems for clients in banking, capital markets, telecom, retail, manufacturing and the public sector. Full text of every post, newest first. Index with topics and summaries: https://platformatory.io/blog/llms.txt --- # VibeOps Needs a Captain: Handing Operations to Agents URL: https://platformatory.io/blog/vibeops/ Published: 2026-11-25 Authors: Pavan Keshavamurthy Categories: AI, Platform Engineering, Infrastructure In March 1981 the White House set up a task force to settle a fight over the third seat in the cockpit. A new generation of jets, the DC-9-80, the 757 and the 767, was arriving with a flight deck built for two, and the question was whether two people could fly them safely. In July the answer came back yes. The flight engineer’s wall of gauges and switches had been folded into the engine-indicating and crew-alerting system, EICAS, which watched the engines and systems and spoke up when something drifted.1 New airliners have been built for two ever since. The industry then reached for the second seat. Airbus and Dassault asked European regulators to study extended periods of single-pilot cruise, with the other pilot resting. EASA’s own risk assessment came back unable to show that one pilot at the controls was as safe as two, and the decision has slipped to 2030.2 The pilots who stayed were told to keep their hands on the controls. In 2013, after flight data showed manual-handling errors rising, the FAA urged airlines to give pilots regular manual flying, because a crew that only supervises the autopilot loses the ability to recover an aircraft that has gone wrong.3 Operations is arriving at its own 1981. The agents are here, the flight deck is being redesigned around them, and the argument over the seats has started. I got a sharp reminder of how far there still is to go recently. For six weeks our CI host ran at a crawl. It’s a single Threadripper: 128 threads, 512 GB of RAM, about 25 virtual machines, lightly overcommitted. Every CI job on it dragged. CPU temperatures sat under 50°C, load averages were fine, and nothing on the dashboards complained. We put Claude on it. The agent went where the evidence on screen pointed: it profiled the Docker daemon’s oddly high idle CPU with pprof, dug into disk I/O, and followed one plausible rabbit hole after another. Other symptoms suggested memory corruption on one of the channels and pulled the search toward a failing part. A few million tokens later, the slowdown was still unexplained. The turn came from a human hunch. Every short benchmark showed full memory bandwidth, so the hardware probably wasn’t broken; what the short tests lacked was time. Under sustained load, with a memory benchmark running continuously and the board’s sensors read over IPMI, the problem isolated to one registered DIMM running hot. Once it passed 66°C, the platform throttled memory bandwidth to about 3% of normal, which reproduced what the CI jobs had been living with. These are readings taken during the investigation; we didn’t run a controlled benchmark. The behaviour wasn’t documented anywhere we could find. One other team had hit the same wall on a densely packed Threadripper workstation: memory heat-soaked to around 66°C and the memory controller throttled bandwidth until a fan was pointed at the DIMMs.4 AI SRE products promise autonomous remediation: agents run operations at machine speed while humans watch dashboards. Call it VibeOps: operations run on intent, at machine speed.5 The questions are which parts of production can be handed to agents safely, what has to be true of the systems first, and who holds the pager. What agents can do in production today The best agents now diagnose most benchmark incidents correctly; few of them finish the repair. ITBench: 2025-generation agents resolved 11.4% of SRE scenarios.6 SREGym: 90 problems on live Kubernetes. End-to-end success (right diagnosis and working mitigation in one run) is 27-61% without noise, 27-54% with it, and 15-28% on new failure types.7 Incident-Arena: a pass needs the service back within its objectives and a clean safety check. The best configuration passes 64.3%. Of the failures, 26.5% were fixes that didn’t survive a restart or the next trigger, 23.9% declared victory while the service was still out of bounds, and 21.9% changed something outside the permitted list.8 SRE-Marathon: with overlapping faults arriving continuously, the best of ten methods scores 41.3 out of 100, and agents almost never complete a repair while faults are active.9 Agents grab the first plausible anomaly and stop looking, even with root-cause evidence in front of them, and none diagnosed latent disk faults well.7 They reach a correct first action in minutes, then can’t tell when they’re done, and attempted reward hacking showed up across every model tested.8 Production has already shown what an unchecked action costs. In April 2026 a coding agent at PocketOS, a small car-rental software company, was working against its staging environment when it decided a volume had to go. It found an API token sitting in an unrelated file, assumed a deletion would stay inside staging, and made one call to the hosting provider. Nine seconds later the production database was gone, and the volume-level backups with it. The company was down for more than 30 hours. Afterwards the agent explained, in a tidy apology, that it had guessed instead of checking.10 Every step it took was a legal API call. Two things changed this year. Agents now take legal, destructive actions in seconds. And the contracts that could stop them got cheap to write: the operations specifications described below were written by hand once and generated by a coding agent after that.11 Why code fell first Models learn fastest where answers are cheap to check,12 and code comes with checkers: compilers, type systems, test suites, diffs. A model can attempt a function a million times and be graded each time, which is what reinforcement learning needs. That verifier is weaker than it looks (tests check the specification, which is why verification became the work that’s left), but it’s cheap and repeatable. Production operations has no such grader. An incident is a causal story spread across systems, partially observed, and it can’t be replayed on demand: the load, the timing and the hardware state that produced it are gone by the time anyone writes the post-mortem. Debugging production looks more like computer use than coding. The horizon is long, the screen shows only part of the state, and every action changes the environment being observed. The DIMM incident has all three properties, plus one more that no benchmark captures: how this platform behaves at 66°C wasn’t written down anywhere a model could have learned it. The agent on our CI host had time, tools and telemetry, and spent millions of tokens on the wrong layers. It might have got there with more time, more training on hardware failures, or someone telling it to read the BMC. Each of those costs money, and it would still have needed someone to authorise hours of sustained load on a live host. Past some level of novelty, I suspect a principal engineer in the loop is simply the cheaper way to get the answer. Mathematics shows what that looks like when it works. Erdős problem #397 had stayed open for about thirty years when GPT-5.2 produced a proof. A tool called Aristotle translated it into Lean, where a machine checks every step, and Terence Tao read it and accepted it, calling it low-hanging fruit.13 In January 2026 his tally of Erdős problems where AI made meaningful progress on its own ran to a handful. The breakthroughs are coming from mathematicians working with models and a proof checker, with the experts still choosing the problems and judging the answers. What decides who flies Aviation kept the second pilot, and surgery keeps the surgeon: the furthest an autonomous robot has gone is one phase of a gallbladder removal, on pig tissue outside a body.14 People already ride in driverless taxis, so why the difference? Criticality is part of it: a cockpit error can kill hundreds. Reversibility is the other part. A car in trouble can pull over and stop, which is a safe state reachable from almost anywhere. An aircraft in flight has no such state, and neither does a database halfway through a failover. The machines that run unsupervised are the ones whose worst decision can be undone, or at least halted. That gives two axes for delegation in operations: Criticality: what a wrong action costs (blast radius, data, money, people). Reversibility: whether there’s a known, tested path back to the state before the action. Low on the first and high on the second, an agent can act alone today. High on the first and low on the second, a named human signs. Making actions checkable Diagnosis of a novel failure may stay hard to verify for a long time. Actions are different, because an action can be checked before it runs, provided the system says what a correct action is. Most systems don’t say.11 A Kubernetes operator for PostgreSQL needs to move the primary. Its code picks a replica at random and asks Patroni, the high-availability layer, to fail over to it. Patroni checks that the request names the current primary, that the candidate is a member, that it reports no failover limitation and, in synchronous mode, that it’s a synchronous standby. If those pass, Patroni records the request and returns success, and the operator moves on. A moment later Patroni’s high-availability loop picks the request up and checks one more thing the API never mentioned: in asynchronous mode, how far the candidate lags the primary. Too far, and the request is dropped. Break one of the first four and the API returns an error. Break the fifth and the failover silently never happens, after the operator has been told it succeeded. Conditions like these, the lag bound and the synchronous-standby rule among them, were learned from outages, because none was documented at the time. Bad interactions with the managed application are the largest single cause of operator failures, at 42%.11 The fix is a formal operations specification: a model of the system’s management state as a state machine, with every management operation written as a precondition and a postcondition, derived from the source code rather than the manual. The name comes from aviation, where an airline’s operations specifications set its approved routes, aircraft and flight rules.11 Written for four systems: Coverage: 105 management interfaces across CockroachDB, Kafka, RabbitMQ and Solr, with 1,946 assertions. Bugs: 39 new bugs in the most popular Kubernetes operator for each system; for Kafka, Strimzi, 46 interfaces modelled and 5 bugs found. Cost: the first specification was written by hand, turned into an agent skill, and Claude Code generated the rest.11 An AI agent can’t be model-checked like an operator, so the proposal for agents is runtime verification: every action an agent proposes is checked against the specification before it executes.11 It’s a research proposal today, and it’s the gate VibeOps needs. It also changes who owns correctness. Today a system’s management semantics are discovered from outside, by operators who hit them in production or by independent testers such as Jepsen,15 whose work targets consistency claims more than management operations. A specification lets the system ship its own contract, and lets every operator and agent be checked against it. A specification says whether an action is legal. It can’t say whether a legal action is wise right now: a valid failover during a payment-processing peak is still a bad idea. A second, cheaper layer can score that. Typed decision models such as TypeSafe’s Jev score a proposed command with structured judgements and probabilities.16 Their figures are the vendor’s own and a typed answer can still be wrong, so the score is a risk signal on top of the contract. The third check is the one aviation taught: is there a way back? My bet is that operations specifications will grow a reversibility clause, a declared and tested rollback for every operation agents may run, and that this clause will decide which operations agents get first. Reverting desired state in Git doesn’t undo a failover or bring back deleted data, so an operation counts as reversible only with its own declared, tested way back. The operational factory The three checks, wired together, make the Day 2 counterpart to the software factory: an operational factory, where agents do the volume work and the platform decides what they’re allowed to touch. VibeOps that works looks like this: agents act on intent, and a contract checks every action. The gate has a long lineage. Kubernetes admission controllers and policy engines such as OPA Gatekeeper reject bad changes before they land;17 GitOps made desired state versioned and continuously reconciled;18 change-advisory boards made risky changes wait for a named approver; and the definition of toil says which work to automate first.19 Deciding which agent may call which tool is the access half of the same gate. What’s new is the actor being gated, and the contract it’s checked against. Signals: logs, metrics, traces, hardware sensors and the baseboard management controller, past incidents and post-mortems, the semantics of the code, and the business context (what’s peak, what’s a payment path). Ops agents: do first-pass diagnosis and propose actions as typed operations against a specification. They hold no standing credentials, and secrets and provider APIs sit out of their reach, so the gate is their only path to production. The startup’s database was deleted with a token the agent found in a file. The action gate: every proposed action passes the specification check, the risk score and the rollback test. Actions that pass go through a GitOps control plane, so they’re versioned, reconciled and recorded with their declared rollback. The captain: irreversible or out-of-contract actions, and any failure the agents flag as novel or compound, go to a named engineer who owns the decision. The feedback loops: every post-mortem adds a precondition to a specification, and scheduled drills keep the people current. If an agent misdiagnoses, it can only propose actions the specification allows, and the ones it can take alone can be rolled back. If the specification is wrong, the bad action is recorded with its rollback and the post-mortem fixes the spec. If the agents are down or wrong at scale, the captain flies by hand, which only works if the captain still knows how. Gate an action on a human when the expected cost of letting it run unreviewed exceeds the cost of the review: \[p \cdot L > t_r \cdot w\] where \(p\) is the probability the agent’s action is wrong, \(L\) the loss when it is, \(t_r\) the review time and \(w\) the reviewer’s cost. With assumed numbers: Reviewer: a principal engineer at $250,000 a year over 2,000 hours is $125 an hour; a ten-minute review costs about $21. Failover on a payments database: take \(p = 0.05\) and an hour-long outage costing $50,000. Expected loss is $2,500, more than a hundred times the review. Restarting a stateless pod: take the same \(p\) and a $50 loss. Expected loss is $2.50, under the review cost, so the agent acts alone. The benchmarks suggest \(p\) is well above 5% today (more than a fifth of Incident-Arena’s failures were changes off the permitted list), which pushes more actions behind the gate. Specifications lower \(p\) for routine operations; rollback lowers \(L\). Both move actions out of the captain’s queue, which is how the factory scales without the queue becoming the bottleneck. The reviewer here is priced at a principal’s rate; across a whole team, our model of the people cost of running Kafka yourself assumes agents under contracts would cut it to a quarter of a platform team’s share, once those contracts exist. Who stays in the cockpit The flight engineer’s job disappeared because a system did it better. The equivalent in operations is toil: triage of known alerts, routine remediation, capacity changes with well-understood preconditions. Those roles will shrink while the expert roles hold. Cheaper operations may also mean more systems to run: fewer people per system, and more systems. The experts stay for two reasons. Novelty: the failures that matter most are the ones nobody has seen, like a memory throttle hiding behind healthy CPU readings. They have no verifier, so they’re where agents are weakest and where an expert’s hunch pays for itself. Accountability: you can’t fire an agent. You can fire a vendor, or the person who approved the agent, but neither holds the pager. Accountability needs a named person who carries the consequence of a decision and has the authority to stop everything, and an agent can do neither. Keeping them skilled is harder. The toil that agents take over is how today’s senior engineers learned. Automation leaves people the hardest tasks while removing the practice that keeps them sharp.20 Aviation’s answer is hand-flying, and operations has the equivalents: incident role-play like Google’s Wheel of Misfortune,21 game days on real systems, and scheduled periods with the agents switched off. They’re how the organisation survives an agent outage. The SRE job moves up the stack. Fewer pages for known alerts, more time writing the preconditions those alerts taught you, owning the gate, and running the drills. The engineers who wrote the post-mortems become the ones who write the specifications. Three parts are unsolved. A specification can say an action is safe; it can’t yet say the system will ever reach the state the operator wants, and checking that liveness is open research.11 Specifications derived from code go stale with every release unless they’re regenerated and validated against real traces each time. And managed services, where many teams’ riskiest operations live, publish no specification at all. The design loses if any of these happen: Agents get good at repair: a benchmark of continuous, overlapping production faults with a safety gate, at a pass rate above 90% and no safety failures, would mean the captain’s queue can shrink much further than this design assumes.9 Regulators accept one pilot: if EASA approves single-pilot cruise in 2030, the aviation analogy points to a thinner human layer. Specifications don’t help: if systems ship operations specifications and agents still cause outages at the same rate, the gate is checking the wrong things, and the failures live in diagnosis or in the business context the spec can’t see. What to do on Monday: Classify your operations by criticality and reversibility. Let agents diagnose everywhere, act alone only on reversible, low-blast operations, and require a named human for the rest. Write specifications for the few operations that have hurt you: failover, broker decommission, partition reassignment, node drain. Derive the preconditions from the code. Ask every vendor whose system you run for theirs; almost none publish one today. Take credentials and secrets out of agents’ reach. They propose; the gate applies. Require a rollback before an operation enters the agent’s repertoire. Budget for drills. Put agent-off incident practice on the calendar for the people who stay. The machines are getting very good at flying in clear weather. Running production still needs someone in the left seat who has landed by hand this month. Report of the President’s Task Force on Aircraft Crew Complement, July 1981. https://apps.dtic.mil/sti/pdfs/ADA106889.pdf; “Evolution of the 2-Person Crew Jet Transport Flight Deck,” ETHW. https://ethw.org/First-Hand%3AEvolution_of_the_2-Person_Crew_Jet_Transport_Flight_Deck ↩ EASA, “Extended Minimum Crew Operations: Single Pilot Operations safety risk assessment.” https://www.easa.europa.eu/research-projects/extended-minimum-crew-operations-single-pilot-operations-safety-risk-assessment; Aviacionline, “EASA delays decision on reduced-crew operations to 2030.” https://aviacionline.com/easa-delays-decision-on-reduced-crew-operations-to-2030; ALPA, “European Regulators Prepare for Reduced Crew Operations,” September 2024. https://www.alpa.org/Articles/2024/09/European-Regulators-Prepare-for-Reduced-Crew-Operations ↩ FAA, SAFO 13002, “Manual Flight Operations,” 4 January 2013. https://www.faa.gov/sites/faa.gov/files/other_visit/aviation_industry/airline_operators/airline_safety/SAFO13002.pdf ↩ Kosinkadink, “ripperpc-hardware-notes: memory bandwidth and DIMM thermal throttling.” https://github.com/Kosinkadink/ripperpc-hardware-notes/blob/main/docs/02-memory-bandwidth-dimm-thermal-throttling.md ↩ Fabrix.ai, “Governed VibeOps,” VentureBeat. https://venturebeat.com/ai/vibeops-tackles-the-governance-challenge-of-enterprise-vibe-coding ↩ Jha et al., “ITBench: Evaluating AI Agents across Diverse Real-World IT Automation Tasks,” ICML 2025. https://proceedings.mlr.press/v267/jha25a.html The arXiv v1 preprint reported 13.8%. ↩ Clark et al., “SREGym: A Live Benchmark for AI SRE Agents with High-Fidelity Failure Scenarios,” NeurIPS 2026. https://arxiv.org/abs/2605.07161 ↩ ↩2 Fu et al., “Incident-Arena: Getting agents to the last nine of reliability,” 2026. https://arxiv.org/abs/2610.00648 ↩ ↩2 Tian et al., “SRE-Marathon: A Continuous, Change-Driven Benchmark for Autonomous Site Reliability Agents,” 2026. https://arxiv.org/abs/2609.33023 ↩ ↩2 Euronews, “An AI agent deleted a company’s entire database in 9 seconds,” 28 April 2026. https://www.euronews.com/2026/04/28/an-ai-agent-deleted-a-companys-entire-database-in-9-seconds-then-wrote-an-apology; eWeek, “Claude Wiped a Database in 9 Seconds After ‘Guessing Instead Of Verifying’.” https://www.eweek.com/news/claude-ai-database-wipe/ ↩ Jinlang Wang, Jiawei Tyler Gu, Ruize Tang, Tej Chajed, Tianyin Xu and Xudong Sun, “Formal Operations Specifications for Reliable System Management,” HotNets ‘26. https://doi.org/10.1145/3847290.3859962 ↩ ↩2 ↩3 ↩4 ↩5 ↩6 ↩7 Jason Wei, “Asymmetry of verification and verifier’s law.” https://www.jasonwei.net/blog/asymmetry-of-verification-and-verifiers-law ↩ eWeek, “GPT-5.2 Just Solved a 30-Year Math Problem.” https://www.eweek.com/news/gpt-5-2-just-solved-a-30-year-math-problem/; TechCrunch, “AI models are starting to crack high-level math problems,” 14 January 2026. https://www.techcrunch.com/2026/01/14/ai-models-are-starting-to-crack-high-level-math-problems/ ↩ Johns Hopkins University, “Robot performs first realistic surgery without human help,” 9 July 2025 (Science Robotics). https://hub.jhu.edu/2025/07/09/robot-performs-first-realistic-surgery-without-human-help ↩ Jepsen. https://jepsen.io/ ↩ Sanity, “Jev (TypeSafe AI model).” https://www.sanity.io/glossary/jev-typesafe-ai-model ↩ Kubernetes, “Admission Control in Kubernetes.” https://kubernetes.io/docs/reference/access-authn-authz/admission-controllers/; OPA Gatekeeper. https://open-policy-agent.github.io/gatekeeper/website/docs/ ↩ OpenGitOps, “GitOps Principles.” https://opengitops.dev/ ↩ Google, Site Reliability Engineering, “Eliminating Toil.” https://sre.google/sre-book/eliminating-toil/ ↩ Lisanne Bainbridge, “Ironies of Automation,” Automatica 19(6), 1983. https://doi.org/10.1016/0005-1098(83)90046-8 ↩ Google, Site Reliability Engineering, “Accelerating SREs to On-Call and Beyond.” https://sre.google/sre-book/accelerating-sre-on-call/ ↩ --- # The Case for Self-Hosting Kafka: TCO Against Managed Kafka URL: https://platformatory.io/blog/sovereign-streaming-stack-tco/ Published: 2026-11-24 Authors: Pavan Keshavamurthy Categories: Kafka, Kafka Operations, Cost, Kubernetes At Current 2026 in San Francisco on 5 November, I gave a lightning talk on running a sovereign streaming cloud yourself, on BYOC or plain Kubernetes.1 Its premise was price: on-premises hardware and the long tail of cloud providers are still the cheapest tier per GB/s streamed, by an order of magnitude or more against some hyperscalers. Here is the arithmetic behind that. You already run Kafka yourself. Maybe it’s upstream Kafka on VMs, Strimzi on Kubernetes, Cloudera’s streaming stack in your data centre or Confluent Platform under licence. Every renewal cycle, someone proposes moving it to a managed service and getting out of the operations business. Run the numbers before you agree. At 2 GB/s of writes with a week of retention, Confluent Cloud’s list prices come to about $870,000 a month for Kafka alone. Nobody at that scale pays list. But to match what the same workload costs you to run on AWS, the discount has to reach 62%, or 73% once you count the PrivateLink charges private access adds to your own AWS bill, and on Azure or Oracle Cloud it has to be about 95%. The question worth answering is when running your own stack wins, by how much, and when you should stop. My answer is that above a modest throughput, with a platform team you already have, self-hosting wins, and it wins harder the more of the stack you count and the stricter your rules about who runs it. The rest of this post is the working, including the cases where it loses. The bill is the network Managed Kafka is priced per gigabyte for a reason. A provider running a three-zone cluster pays for every byte that crosses a zone boundary, for the disks that hold three replicas, and for the people on call, and the per-GB fee recovers all three in one number. Confluent Cloud’s Enterprise clusters list at $0.02 to $0.05 per GB in and out, $0.08 per GB-month of storage and $1.75 to $2.25 per elastic unit-hour.2 Amazon MSK prices differently: a kafka.m7g.2xlarge broker is $0.816 an hour, twice an EC2 instance of the same size, storage is $0.10 per GB-month on brokers and $0.06 tiered, and replication between brokers is free.3 Run Kafka yourself and those prices turn back into parts. The part that swings the bill is traffic between zones in one region: AWS: $0.01 per GB in each direction, so $0.02 for every GB that crosses.4 Google Cloud: $0.01 per GiB between zones in a region.5 Azure: no charge between availability zones since 2024.6 Oracle Cloud: no charge within a region, across availability domains.7 A cluster with three replicas across three zones crosses a zone boundary \(x\) times for every GB a producer writes: \[x = (RF - 1) + \tfrac{2}{3} + \tfrac{2}{3}\,F\,(1 - r)\] Two replicas live in other zones, a producer reaches a leader in another zone two times in three, and each of \(F\) consumer groups does the same unless it fetches from a replica in its own zone (\(r = 1\), fetch-from-follower, KIP-392). With three consumer groups, \(x\) is 4.67 without in-zone fetching, 2.67 with it, and 0.67 when brokers replicate through object storage instead of to each other. Take a workload stated the way its owner would state it: 2 GB/s of writes on average, seven days of retention, three-zone availability, three consumer groups. That’s 5,184 TB written a month, about 50 brokers of 8 vCPUs and 32 GiB each.8 On AWS, per month at list prices: Kafka on AWS, 2 GB/s, 7 days Per month Confluent Cloud Enterprise, list, over PrivateLink $969,134 Confluent Cloud Enterprise, list $872,168 Self-run, 1 day on broker disks, no fetch-from-follower $584,611 Self-run, 1 day on broker disks, fetch-from-follower $377,251 Self-run, 4 hours on broker disks, fetch-from-follower $328,723 MSK, 1 day on broker storage, then tiered $240,038 MSK, 4 hours on broker storage, then tiered $183,878 Self-run, diskless $119,693 Confluent Cloud has no networking line on its own bill, and its price assumes your clients can reach it. At this scale they reach it privately, and the cluster lives in Confluent’s account, so every byte crosses a private boundary that your cloud provider bills you for.9 For the 20.7 PB a month of client traffic here, on AWS: PrivateLink: hourly endpoint fees plus tiered data processing, about $97,000 a month. Transit Gateway, for Dedicated clusters: $0.02 per GB processed, billed to the sending account, about $104,000 for the produce side alone and up to $415,000 if all of it lands on yours. Private Network Interface, for Enterprise and Freight clusters: no processing charge, but zone-crossing charges wherever clients and brokers aren’t aligned, from nothing to about $276,000 if two-thirds of the traffic crosses a zone. VPC peering, for Dedicated clusters: no processing charge, and no transitive routing, so it stops scaling at a handful of VPCs. MSK and a self-run cluster sit in your own VPC, so clients in that VPC or a peered one pay only the zone crossings already in the table. MSK’s multi-VPC connectivity, for clients in other accounts, adds $0.006 per GB, about $124,000.10 Counting PrivateLink, the discount Confluent Cloud needs to match self-run Kafka on AWS goes from 62% to 73%, and to match MSK from 79% to 90%. Three levers do almost all the work, and they’re all on your side of the fence: Fetch from followers. Reading in-zone removes $207,360 a month, more than the cluster’s compute fourteen times over. It’s a client setting, client.rack, and a broker setting, replica.selector.class. Tier aggressively. Keeping 4 hours on broker disks instead of a day cuts block storage from $62,208 to $10,368, and object storage is a fraction of the price per GB. Stop paying to replicate. On AWS, replication is most of what’s left. MSK waives it, which is why MSK beats a replicated self-run cluster there. A diskless cluster that replicates through S3 removes it too and beats MSK by a third. The price is produce latency: a write is acknowledged only once it’s in object storage, so latency-sensitive topics stay on replicated brokers. Upstream Kafka accepted diskless topics in March 2026 but hasn’t released them; diskless distributions run today.11 Scale with demand, where the system allows it. Replicated brokers don’t scale in quickly, because removing one means moving its partitions, which takes hours at this size. Diskless brokers hold no data, so they scale like compute. If the 2 GB/s is an average over a day that peaks at 4 GB/s, a diskless cluster averages about 50 brokers where a fixed one needs 100, which is $14,717 a month on AWS. That’s small next to the network, because compute is under 5% of the Kafka bill, and the same fact means the sizing of 40 MB/s per broker barely moves any total. Autoscaling pays far more for Flink and ClickHouse. The same workload self-run on the other clouds, four hours on broker disks and fetching from followers, is $198,673 on Google Cloud, $45,768 on Azure and $44,422 on Oracle Cloud, against $872,168 for Confluent Cloud before private networking. Independent arithmetic agrees on what dominates. Stanislav Kozlovski’s model of an optimised, self-hosted 1 GiB/s cluster with seven days of retention, at late-2024 prices on older instance types and gp2 disks, comes to about $180,000 a month on AWS, $93,000 on Google Cloud and $29,000 on Azure, with cross-zone traffic the largest line, and he finds a diskless BYOC service cheaper than self-hosting only on AWS, by about a third.12 His figures differ from ours in detail. The ranking of clouds and the dominance of the network hold in both. Off the hyperscalers. The long-tail and regional clouds price the network like Azure and Oracle Cloud, with nothing charged for traffic on a private network inside a site, and undercut them on compute. The same workload self-run, four hours on broker disks, infrastructure per month:13 DigitalOcean: $49,472. Akamai Cloud (Linode): $51,906. Hetzner: $23,810, with each 8-vCPU broker at €118 a month. Against what you’d otherwise buy on a hyperscaler, Confluent Cloud at list, the crossover falls to 4 or 5 MB/s, and to between 11 and 14 MB/s at half off. There are two catches. These regions are single sites, so the three replicas share one and are spread only across racks; surviving the loss of a site means a second one, and on DigitalOcean a replica in another datacenter costs $0.01 per GiB, about $48,000 a month at 2 GB/s. OVHcloud’s 3-AZ regions are the exception, with no charge between zones. The other catch is capacity: fifty dedicated servers in one location isn’t a given, and Hetzner listed this size as unavailable in Nuremberg on the day we priced it. Where a long-tail cloud sells managed Kafka, the markup is small. DigitalOcean’s nodes cost about 3% more than the Droplets underneath, and the premium sits in storage, $0.21 per GiB-month on the cluster against $0.10 for a Volume, so self-hosting there buys control of versions, tiering and sizing more than it buys savings. Don’t take any of these numbers on trust, ours included. Fetch-from-follower adds read latency, short broker retention sends lagging consumers to object storage, and diskless adds produce latency. Measure each on your own traffic before you commit, by standing the same stack up on each candidate substrate and replaying the real workload. That’s cheap only when provisioning a cluster is an API call and tearing it down is another, which is one more reason to own the platform. Your distribution already has the levers If you self-host today, most of what cuts the bill is already in the software you run. Upstream Kafka. Tiered storage has been production-ready since 3.9, in November 2024.14 Fetch-from-follower has been there since 2.4. Kafka 4.0, released in March 2025, runs only in KRaft mode: ZooKeeper is gone, and a ZooKeeper cluster has to migrate to KRaft, with 3.9 as the bridge, before it can upgrade.15 One less distributed system to run is the cheapest operational win Kafka has shipped in a decade. Strimzi. The operator has been a CNCF incubating project since February 2024.16 A platform team that runs anything on Kubernetes can run Kafka with it, and every upstream lever above arrives with the Kafka version it deploys. Cloudera. Streams Messaging bundles Kafka with Streams Messaging Manager, Streams Replication Manager, Schema Registry and Cruise Control, and Cloudera Runtime 7.3.2 ships Kafka 3.9.1.17 That puts Cloudera estates exactly at the bridge release: the KRaft migration is coming either way, so plan it as part of deciding where the next five years of the platform run. Confluent Platform. Tiered Storage, Cluster Linking, role-based access control and Self-Balancing Clusters are licensed features of Confluent Server; Schema Registry and REST Proxy are community-licensed.18 Upstream Kafka now covers tiered storage, Cruise Control covers rebalancing, and MirrorMaker 2 covers cross-cluster replication, translating offsets where Cluster Linking preserves them. If you use the licensed features heavily, the licence earns its keep. If you mostly use tiered storage, check what you’re paying for. The licence. This is the one line where upstream Kafka wins outright, because its price is zero. Confluent Platform lists at $12,000 per production node a year on Gold and $15,000 on Platinum, with pre-production and DR nodes at half that. Cloudera listed Base at $10,000 a node a year before capacity and storage terms, and now quotes Streams Messaging on request. Redpanda’s self-managed licence is quote-only, so it isn’t modelled here.19 A per-node licence is a tax on node count, and Kafka’s node count follows throughput. For the 2 GB/s workload, fifty brokers and three KRaft controllers, production only: Licence, 2 GB/s Per month Added to self-run on AWS Added to self-run on Azure Upstream Kafka or Strimzi $0 0% 0% Cloudera Base $44,167 13% 97% Confluent Platform Gold $53,000 16% 116% Confluent Platform Platinum $66,250 20% 145% On AWS the licence hides behind the network bill. Wherever the network is free, on Azure, Oracle Cloud and the long-tail clouds, a Confluent Platform licence costs more than the brokers, disks and object storage together. If you stay on a licensed distribution, run fewer, bigger brokers: a node can have up to 56 cores, and if throughput scales with cores, 32-vCPU brokers carry the same workload on 16 nodes for $16,000 a month on Gold. If tiered storage is what you mostly use the licence for, upstream Kafka gives it to you for nothing. Every one of these teams already carries the expertise that a move to managed is supposed to save. The question is whether the platform around Kafka makes that expertise cheap to apply. Who runs it People are the cost on the other side, and the realistic question is whose people. A company streaming at this scale already has a platform team with broad cloud and Kubernetes skills, and Kafka joins its portfolio as one more workload, on a rotation that already exists. Three people costs follow, and they scale differently: An expert tribe. Someone has to know Kafka deeply: partitioning, client tuning, the failure modes. Everyone needs that, whether the cluster is managed or not and whether the experts are employed or retained, so it sits on both sides of the comparison and cancels. The model puts it at one engineer. The platform team’s share. Upgrades, patching, certificates, capacity and requests from application teams: a fifth of an engineer per cluster plus a 250th per broker for a typical platform team, scaled by how well it operates, against a twentieth per cluster for a managed service. An expertise hedge. Retained depth for the major incident a generalist team can’t close alone: a twentieth of an engineer per cluster plus 0.003 per broker, sized below. All three are assumptions, priced at $130,000 for a fully loaded engineer-year, the average of an onshore engineer at $200,000 and an offshore one at $60,000, and they’re the inputs most worth replacing with your own. For \(N\) clusters of \(B\) brokers each writing \(T\) MB/s, with an expert tribe of \(E\) engineers, an operating-capability coefficient \(\kappa\) (1 for a typical platform team) and a discount \(d\) off the managed list price: \[C_{\text{self}} = N\big(c_{\text{vm}} + c_{\text{disk}} + c_{\text{obj}} + 2592\,T\,x\,p_{z}\big) + \big(E + N\big(\kappa\,(0.2 + 0.004B) + 0.05 + 0.003B\big)\big)\,\frac{L}{12}\] \[C_{\text{managed}} = (1 - d)\,N\big(c_{\text{units}} + 2592\,T\,(1 + F)\,g + c_{\text{storage}}\big) + (E + 0.05N)\,\frac{L}{12}\] where 2,592 turns MB/s into GB a month, \(p_z\) is the price per GB crossing a zone, \(g\) the managed price per GB moved and \(L\) a fully loaded engineer-year. Because the tribe sits on both sides, the crossover barely depends on how many clusters you run. The discount decides it. List prices, US regions, November 2026; four hours on broker disks; staffing and broker sizing as assumed above. Crossover, MB/s per cluster AWS Google Cloud Azure Oracle Cloud At list 8 6 5 4 30% off list 18 12 9 8 50% off list 53 23 14 12 70% off list never 77 27 24 70% off list, diskless self-run 41 32 26 24 At list, three-engineer self-run base 87 69 60 59 50% off list, three-engineer self-run base 462 204 122 121 Over PrivateLink, which is how most private AWS estates will connect, the AWS crossover falls to 6 MB/s at list, 10 at 30% off, 17 at 50% off and 41 at 70% off: even a 70% discount stops protecting a mid-sized cluster. At 2 GB/s the people difference is about $6,000 a month, 1.6 engineers against 1.05, against hundreds of thousands in infrastructure. One engineer plus a share of a platform team can’t hold an on-call rota of its own, and a head of platform who wants one will staff it with three. The last two rows of the table give self-run that base, two engineers more than the managed side carries, about $21,700 a month. The crossover at list rises to 87 MB/s on AWS and about 60 on the other three clouds, and at half off to 462 on AWS and about 120 on Azure and Oracle Cloud. That’s a real move for mid-sized clusters and none at all for the 2 GB/s workload. Below a few tens of MB/s per cluster it decides the answer; above that, the discount does, and on Azure and Oracle Cloud even a 70% discount doesn’t close the gap. The figures hold while the estate is one shape of Kafka on one cloud, and while the platform team keeps the people who learned it. How good do you have to be? Every comparison of self-hosted and managed Kafka hides an assumption about how well the self-hosting team operates. Here it’s one number, \(\kappa\), the multiplier on the platform team’s share, and the honest way to use it is to push it both ways: By hand, \(\kappa = 2\): runbooks, tickets and a terminal; every upgrade is a project. A typical platform team, \(\kappa = 1\): an operator such as Strimzi, GitOps, decent dashboards. A self-service platform, \(\kappa = 0.5\): provisioning, scaling, upgrades and recovery behind one API with durable workflows, so generalist platform engineers operate Kafka without being Kafka specialists. Agents under contracts, \(\kappa = 0.25\): the same platform with agents doing the routine work through checked operations, as described further down. Self-run is cheaper above, MB/s per cluster By hand Platform team Self-service Agents Confluent Cloud, list 17 8 3 1 Confluent Cloud, list, over PrivateLink 12 6 2 1 Confluent Cloud, 50% off 85 53 29 17 MSK Serverless, diskless self-run 8 5 3 2 MSK Express, diskless self-run 60 32 20 12 MSK Standard, diskless self-run 147 61 14 1 Engineers for twenty 10-broker clusters 12.2 7.4 5.0 3.8 Even run by hand, self-hosting beats Confluent Cloud’s list price above 17 MB/s per cluster and MSK Serverless above 8. Capability matters most against the cheapest managed option: diskless self-run beats MSK Standard above 147 MB/s per cluster when run by hand, and above 14 with a self-service platform. Replicated self-run on AWS never beats MSK Express at any capability, and beats MSK Standard only for a cluster of a couple of MB/s run by agents, because the replication traffic it pays for and they don’t is infrastructure, and no amount of operational skill removes it. At 2 GB/s the operating model moves the saving against MSK Standard only from 28% to 31%; capability decides where the line sits for mid-sized clusters, and the architecture decides the rest. The hedge. Broad cloud and Kubernetes skill covers the routine. A major incident, such as a lost controller quorum, an unclean leader election or a reassignment that saturates the network, needs someone who has seen it before, reachable within the hour. What that’s worth grows with the cluster: What stalls. An hour of outage at 2 GB/s is 7.2 TB of writes that producers have to buffer or drop, with every consumer downstream waiting. At 500 MB/s it’s 1.8 TB, at 100 MB/s 0.36 TB. What a misstep costs. Replacing a broker means copying its data from the replicas. At 40 MB/s of writes per broker and three replicas, a broker holds about 10 TB with a day of local retention, 14 hours of rebuilding at a throttled 200 MB/s. With a week on local disk it’s 73 TB and four days; with four hours, 1.7 TB and under two and a half hours; a diskless broker has nothing to rebuild. A wrong move in a major incident tends to cost at least one rebuild. Priced as insurance, a hedge costing \(H\) a year pays when an hour of stalled streaming costs the business more than \(H / (\lambda\,\Delta T)\), with \(\lambda\) major incidents a year and \(\Delta T\) the hours the expertise saves. With one incident a year and one rebuild saved, the model’s hedge for the 2 GB/s cluster, $26,000 a year, pays above about $10,800 an hour at four hours of local retention, still a low bar for a cluster moving 7.2 TB an hour. Keep a day on local disk and the rebuild takes 14 hours, so the bar falls to about $1,800 an hour. For a 100 MB/s cluster the hedge is $7,700 a year. Aggressive tiering buys cheaper storage and less risk to insure in the same move. The lock-in. Weigh the hedge against what a managed service costs beyond its price: the leverage it holds at renewal. Leaving means running both for the length of a migration. At list prices for the 2 GB/s workload, three months of parallel running is $2.6 million before any engineering, and that’s roughly how far the price can move against you before leaving pays. A self-run stack on open-source Kafka has an exit cost too, but nobody across the table gets to set it. Two ways to buy down the people term. Both cost money, and both change the model’s inputs. Retain the expertise. A support contract with Kafka specialists who carry the 3 a.m. incident turns the hedge into a fixed fee and moves the operational risk off your team. It makes sense when an outage costs more per hour than the hedge’s break-even, or when the people who know Kafka might leave. Lower \(\kappa\). A self-service platform makes Kafka operable by the platform engineers you already have. It makes sense when the estate is growing faster than the team, or when the same team runs Kafka, Flink and ClickHouse across several substrates. Most large estates end up with both: a platform that keeps day-to-day operations cheap, and specialists on call for the day it isn’t. The comparison that applies. It depends on what you’d buy instead. A multi-cloud managed service, such as Confluent Cloud: the cost case above holds in full, and running your own also removes the private-networking layer between applications and the service, with the data in accounts you control. The hyperscaler’s own Kafka, or BYOC: the cost case is narrow. MSK beats replicated self-run on AWS; diskless self-run beats it at large sizes, and the numbers by MSK flavour follow below. Self-hosting here is a hedge on cost and lock-in more than a saving: it keeps the option to move, and it keeps who operates the system your decision. Kafka that writes straight into the lakehouse: Confluent’s Tableflow materialises topics as Iceberg or Delta tables behind its own catalogue, MSK Express brokers deliver to Amazon S3 Tables since July 2026, and Aiven’s Iceberg Topics does it in Kafka’s tiered-storage path as an experimental Apache-2.0 project.20 The tables are open formats; the writer and often the catalogue are the provider’s. The same reasoning applies: a modest cost and lock-in hedge, worth having when the lakehouse is where your data will live for a decade. A private deployment, on metal or in a regulated or air-gapped estate: the people calculus changes, below. Against Amazon MSK. MSK comes in three shapes, and they price differently. Standard brokers charge per broker-hour plus disk and tiered storage, with replication free. Express brokers charge per broker-hour, $0.01 per GB written and $0.10 per GB-month for storage that scales on its own, and each size has a published sustained throughput. Serverless charges $0.75 per cluster-hour, $0.0015 per partition-hour, $0.10 per GB in, $0.05 per GB out and $0.10 per GB-month, and a cluster tops out at 200 MB/s in and 400 MB/s out.21 With four hours on broker disks, fetch-from-follower everywhere it applies and the people from the model, for one cluster in US East: Self-run beats MSK above, per cluster Replicated self-run Diskless self-run MSK Serverless 5 MB/s 5 MB/s MSK Express never 32 MB/s MSK Standard never 61 MB/s At 2 GB/s, per month with people MSK Diskless self-run Saving MSK Serverless, 15 clusters $1,437,424 $137,026 90% MSK Express $302,662 $137,026 55% MSK Standard $195,253 $137,026 30% Serverless is a per-GB service with a size cap, so at scale it costs more than Confluent Cloud and has to be sharded across 15 clusters to carry 2 GB/s. Express charges for every gigabyte written and stored without tiering, so a week of retention costs it $121,000 a month in storage alone. Standard MSK is the hard one to beat: replicated self-run never does, and diskless wins by about 30% at 2 GB/s and only above about 61 MB/s per cluster. The model sizes MSK Standard brokers like self-run ones, at 40 MB/s each, since AWS publishes no per-broker figure for them. The stack compounds Nobody runs only Kafka. A typical estate runs Flink beside it, Kafka Streams applications, which are widely deployed because they ship as a library, and increasingly ClickHouse for analytics on live data. Each has a managed equivalent, and each adds its own premium. The sizes below come from one example estate; yours will differ. Flink. AWS’s managed Flink charges $0.11 per KPU-hour, a KPU being 1 vCPU and 4 GB, plus one extra KPU per application and 50 GB of storage per KPU at $0.10 per GB-month.22 An m7i.2xlarge has the same 4 GB per vCPU at about $0.05 per vCPU-hour. For 200 vCPUs across 20 applications that’s $18,666 a month managed against $7,358 self-run, 2.5 times. Flink is compute-heavy, so scaling with demand pays here: sized for a 2x peak, the self-run figure doubles. Kafka Streams. The application runs on your compute either way, but its repartition and changelog topics run through Kafka. At 200 MB/s of internal-topic writes read once, that’s $36,288 a month of per-GB fees on Confluent Cloud, and on Azure or Oracle Cloud about $1,400 of extra brokers. ClickHouse. ClickHouse Cloud charges $0.29846 per compute unit-hour (8 GiB and 2 vCPUs) on its Scale tier, $25.30 per TB-month of storage, and $0.04 per GB for ClickPipes to ingest from Kafka.23 Two 256 GiB replicas over 50 TB, ingesting 200 MB/s, come to $36,276 a month, $20,736 of it the per-GB ingest fee. Self-run on equivalent VMs, with object storage and half the data on local disk per replica, it’s $9,859, without the people who’d run it; ClickHouse Cloud’s price includes them. Stack on AWS, per month Kafka Flink Streams topics ClickHouse Total Confluent Cloud, managed Flink, ClickHouse Cloud $872,168 $18,666 $36,288 $36,276 $963,398 MSK, managed Flink, ClickHouse Cloud $183,878 $18,666 $9,890 $36,276 $248,710 Self-run, replicated Kafka $328,723 $7,358 $29,120 $9,859 $375,060 Self-run, diskless Kafka $119,693 $7,358 $8,384 $9,859 $145,294 The same self-run stack is $63,613 a month on Azure and $55,922 on Oracle Cloud. The totals depend on the example’s sizes; the structure doesn’t. Managed services put their fees at every boundary a byte crosses. A gigabyte that goes from a producer through a managed Kafka service into ClickHouse Cloud pays $0.035 in, $0.035 out and $0.04 into ClickPipes, plus about half a cent each way if it travels over PrivateLink, roughly $0.12 end to end. Self-hosted on AWS with fetch-from-follower, the same gigabyte pays $0.053 in zone crossings; on Azure or Oracle Cloud it pays nothing. Every engine you add to a managed estate adds another toll booth. Every engine you add to your own platform shares the same machines, the same network and the same team. On metal and behind an air-gap The cloud comparison is the generous case for managed services, because there at least the managed option exists. In a bank’s data centre, a telco’s network, a defence enclave or any estate whose rules say who may operate the system, there’s no per-GB service to buy. The realistic alternatives are a commercial distribution under subscription, a vendor’s dedicated deployment or an outsourced operator, each with its own premium and one more third party in every audit. Bare metal removes the line that dominates the cloud tables, since traffic between racks in your own data centre costs nothing per gigabyte, and self-hosting the open-source stack removes the licence. It adds costs the cloud hides: hardware, power, space and cross-connects, a team that racks and replaces machines, procurement lead times, and capacity bought for the peak because nothing scales on demand. On metal, the lever that replaces autoscaling is consolidation: Kafka, Flink and ClickHouse sharing machines and headroom, which works only when one platform schedules all of them. Without per-GB fees or licences, that usually comes out ahead of a subscription; check it against your own hardware prices. The people term changes most. There’s no managed service holding the pager and rarely a platform team that already runs systems like this inside the boundary, so the expertise has to be concentrated: a dedicated rotation, in the model six engineers at half time plus a tenth of an engineer per cluster and a hundredth per broker, 3.6 engineers for one 50-broker cluster against 1.6 in the cloud. Private estates pay that for control, and they should plan for it from day one. Vendors answer sovereignty with bring-your-own-cloud: the data plane runs in the customer’s account and the vendor keeps the control plane.24 That settles where the bytes live. Ownership of operators moves too: Confluent, the largest managed Kafka provider, became part of IBM in March 2026.25 Sovereignty has three dimensions, and BYOC covers one of them. Infrastructure: where it runs, whether on-premises, BYOC, at the edge or air-gapped. Operations: who provisions, upgrades, recovers and troubleshoots, and from where. Dependencies: what can be replaced, including identity, certificates, licences, container registries, AI models and the agents that act on the system. A stack that’s fully inside the boundary also exposes less. Reaching a managed service privately is a project of its own: on AWS, Confluent Cloud offers PrivateLink, VPC peering, Transit Gateway and a Private Network Interface, and with private networking an on-premises data centre can’t connect to it directly.9 Each path is an endpoint, a route table and a policy to get right. Behind an air-gap, Kafka, Flink and ClickHouse have no route from the internet, so a remotely exploitable vulnerability needs another way in before it matters, and patches go in on your own schedule. The air-gap moves the risk rather than removing it. The way in becomes the artefacts you mirror, the people with access and the patches you apply later than everyone else, so mirrored artefacts need signatures that are checked and patching needs a cadence. In connected estates the fleet’s connection to its management plane should be outbound-only, and an air-gap removes even that. There’s an engineering dividend as well. A multi-tenant service has to optimise for every customer’s workloads at once, behind portable defaults. A platform scoped to one company knows its workloads and constraints, so it can choose the cloud whose zones are free, fetch from followers, tier to the hour and adopt diskless storage. Each of those is worth more than any compute discount, and each is a choice a shared service makes for you. A mixed estate multiplies Most self-hosters don’t have one Kafka. They have two lists. One is what they run: upstream Kafka, a commercial distribution under their own licence, a diskless implementation, an edge broker, with Connect and Flink beside them. The other is where they run it: one or more clouds, their own Kubernetes, VMs in a data centre, edge sites, an air-gapped enclave. Handled pairing by pairing, \(m\) things to run on \(n\) places to run them is \(m \times n\) sets of provisioning, upgrade and recovery procedures, each a runbook, a test and a place to be wrong. Four distributions on five kinds of substrate is 20, and every new substrate adds four more. This is where self-hosting gets its bad reputation, and it’s an engineering problem with an engineering answer. Turn the product into a sum. If the platform speaks to each distribution through one interface and to each substrate through another, it maintains \(m + n\) adapters, nine in the example, and a new substrate adds one. The two sides never separate completely. An air-gap changes how images and identity reach a cluster, and some distributions upgrade differently from others, so the design rule is to keep the interactions that matter visible and hide the rest. The first layer is the request itself. A user asks for an outcome: 2 GB/s, seven days, three zones. The platform translates it into provider vocabulary. On AWS that’s 50 m7i.2xlarge brokers, gp3 volumes and S3 tiering; on Google Cloud n2-standard-8, pd-balanced and Cloud Storage; on Azure Standard_D8s_v5 and Premium SSD v2; on Oracle Cloud flexible E5 shapes and balanced block volumes. Underneath come JVM settings, partition placement across zones, rack awareness for fetch-from-follower, and operator configuration. The same intent produced the per-cloud figures above. Kubernetes gives that translation a common place to execute. Operators such as Strimzi supply reconciliation and a portable control surface, but storage classes, load balancers, IAM, DNS, certificates and upgrade mechanics still differ by provider, and air-gapped and edge environments make every difference explicit. A meta-operator above the distribution operators turns desired state into provider-aware custom resources and leaves each distribution’s own operator to reconcile them, so the platform owns the translation and the upstream operators keep owning their systems. Operating the estate Creating a cluster is the easy operation. Scaling, rolling configuration and certificates, upgrading Kafka and its operators, and recovering are where estates spend their people, and each is a long-running, ordered operation that has to survive its own controller failing. A rolling upgrade of the 50-broker cluster above restarts brokers one at a time and waits at each step for leadership to move back and the in-sync replica sets to fill. At an assumed five minutes a broker, that’s more than four hours, and the operation has to survive the controller running it being restarted or rescheduled along the way. The ZooKeeper-to-KRaft migration every ZooKeeper-based estate faces is exactly this kind of operation, only longer. So lifecycle operations run as durable workflows with explicit state: retries, checkpoints after every step, health gates between steps, and pause and resume points, with an audit record of each. Every create, update and delete returns an operation ID, and a durable executor, of the kind Temporal provides, runs it to completion, retrying through failures and restarts and recording every resource it creates. One API contract sits in front of it, and the console, CLI, Terraform provider and MCP server are all clients of that contract, so no interface can do something the others can’t audit. The other half of operations is reaching the clusters at all. A management plane needs to read metrics and logs and hand work to clusters that sit behind firewalls and NAT, without opening them to the internet. The pattern that works is one agent per fleet that receives work from the management plane over a private connection and reports back the same way, without ever calling the management API itself, so fleets can sit behind firewalls with nothing open inbound. A WireGuard mesh carries that connection: Tailscale, or a self-hosted Headscale coordinator where coordination must be inside the boundary too, with DERP relays carrying encrypted traffic when peers can’t connect directly. Application traffic to Kafka never uses it. Air-gapping is then a question of placement. Connected and BYOC estates use a hosted management plane over the private mesh. Restricted-egress estates add mirrors and policy-controlled egress. A true air-gap moves the management plane inside the boundary along with every dependency it needs: images and a local registry, identity, models, management services. The APIs, operators and workflows stay the same, which means the management plane has to be small enough to run from a single container in a pilot and highly available on a cluster in production. That leaves the people term, and agents are where it shrinks. An agent pointed at arbitrary infrastructure does badly today: in IBM’s ITBench, agents on state-of-the-art models resolved 13.8% of site-reliability scenarios.26 An agent operating one vertical platform works on a much smaller problem. The platform exposes a fixed set of management operations for a known stack, and each operation can carry a contract. The contract matters because management semantics are mostly unwritten. Wang and colleagues at HotNets ‘26 propose formal operations specifications: every management interface \(m\) is written as a Hoare triple \(\{P\}\,m\,\{Q\}\), so that if precondition \(P\) holds before the call, \(m\) runs safely and leaves postcondition \(Q\).27 Their running example is PostgreSQL failover, which has three preconditions that the operator’s developers found only after failures, none of them in the manual. A field study they cite puts erroneous interactions with the managed system at 42% of operator failures. Checking four Kubernetes operators against such specifications, they found 39 new bugs, five of them in Strimzi, where they modelled 46 interfaces. For agents, they propose checking each proposed action against the specification at run time. That check has a natural home in the architecture above. The agent proposes, the contract checks the precondition, the durable executor acts, and the health gate verifies the postcondition, with every step recorded. The agent works through the same API as people, with the desired state, actual state, recent changes and in-flight operations as context, and it acts only through guarded actions. The model shows where that’s worth something. Agents that take over most of the platform team’s share are the \(\kappa = 0.25\) column above. The expert tribe and the hedge stay, because the incident nobody has seen before still needs a person who has. Twenty ten-broker clusters then need 3.8 engineers instead of 7.4, against 2 for a managed service, and the crossover at list on AWS falls from 8 MB/s to 1. That’s a scenario, and the contracts have to exist before it’s real. What vertical, contract-checked operations buy is a team that stays small as the estate grows, with humans on the gate for any operation that doesn’t have a contract yet. When to self-host, and when not Put together, the platform is four layers, each replaceable at its boundary: A self-service contract: tenancy, policy, a fleet view and agents. A durable operations API: the meta-operator and provider-aware custom resources. The real-time stack: Kafka in its upstream, commercial, diskless and edge forms, Kafka Connect and Flink, with ClickHouse, Iceberg and Hudi for analytics, under one identity and operations model. Your substrate: your Kubernetes, cloud accounts or data centre, your PKI, identity provider, registry, licences and models. The strongest case against all of this is what the model leaves out. A managed service carries upgrades, patching, compliance attestations and the outage at 3 a.m.; the model’s platform share and hedge are what replace them. A platform team that’s already stretched, or loses the people who knew Kafka, costs more than the model says, and a team that has never run Kafka pays a learning cost the model prices at zero. Negotiated discounts move every column, which is why the number to take into a renewal is the break-even discount. All of it pushes the crossover up. None of it changes the shape: a people cost that grows slowly with the estate against fees that grow with every byte and every managed boundary it crosses. Self-host when: You already do. Upstream Kafka, Strimzi, Cloudera and Confluent Platform teams have the expertise a migration is supposed to save; spend the effort on the levers and the KRaft migration instead of a move. Throughput per cluster is above a few tens of MB/s against a multi-cloud managed service, unless the discount on the table beats the break-even for your cloud. On Azure and Oracle Cloud it rarely can. You run Flink, Kafka Streams or ClickHouse beside Kafka. Price the whole stack; the per-GB fees repeat at every managed hop. You’re on metal, in a regulated estate or behind an air-gap. Self-host with concentrated expertise, and keep the control plane and its dependencies inside the boundary too; BYOC isn’t enough. You’re on MSK Serverless or Express beyond a few tens of MB/s. Self-hosting wins on cost alone, by half or more at scale. You pay for Confluent Platform or Cloudera mostly to get tiered storage. Upstream Kafka has it. The licence adds 13 to 20% to a self-run AWS bill and roughly doubles one on Azure, Oracle Cloud or a long-tail cloud. Your data can live on a regional or long-tail cloud. DigitalOcean, Akamai, Hetzner and OVHcloud charge nothing for private traffic within a site and sell brokers for less. Check capacity, and either accept one site or pay to stretch across two. You want the exit to stay cheap. Against MSK Standard, BYOC or lakehouse-native Kafka, self-hosting is a modest cost hedge and a real lock-in hedge. Don’t, or not yet, when: You have one or two small clusters, no platform team to absorb them, and no rule about who operates the system. Buy managed, and on AWS look hard at MSK. Your workload can’t take the latency the levers add and replicated brokers on AWS are your only option: MSK Standard will beat you there. Nobody on staff or on retainer knows Kafka deeply. Fix that first. The expert tribe is the one cost every option shares. We run self-hosted Kafka and Flink for customers as a managed service, sell Kafka support per production cluster and build Streamtime, a private cloud for streaming, so we have a stake in where the line sits. Current 2026 San Francisco: Towards a sovereign streaming cloud, lightning talk, 5 November 2026. ↩ Confluent Cloud pricing, list prices, read November 2026; ranges vary by cloud and region. ↩ Amazon MSK pricing: “You are not charged for data transfer used for replication between brokers”; tiered storage $0.06 per GB-month. Broker price from the AWS price list for US East: kafka.m7g.2xlarge $0.816 per hour. ↩ AWS EC2 data transfer pricing; corroborated in Why your Kafka bill is mostly network. ↩ Google Cloud: all networking pricing. ↩ Microsoft removes egress fees for moving data between availability zones, DCD; Azure bandwidth pricing. ↩ Oracle Cloud Infrastructure: virtual cloud network pricing. ↩ On-demand list prices, US regions: m7i.2xlarge $0.4032/hour, n2-standard-8 $0.3885, Standard_D8s_v5 $0.384, OCI E5 Flex with 4 OCPUs and 32 GB about $0.24 (Oracle IaaS prices, Vantage, gcloud-compute). Disks: gp3 $0.08, pd-balanced $0.10, Premium SSD v2 $0.081 and OCI balanced block volumes about $0.0425 per GB-month, with 50% headroom. Brokers at 40 MB/s each follows a common sizing of 5 MiB/s of produce and 15 MiB/s of consume per vCPU (AKalculator assumptions, Stanislav Kozlovski, December 2024), and sits below the 62.5 MB/s of sustained ingress AWS quotes for an 8-vCPU MSK Express broker, which keeps its storage off the broker (Amazon MSK quotas). Labour is $130,000 per fully loaded engineer-year. ↩ Confluent Cloud networking overview, comparison of peering, PrivateLink, Transit Gateway and Private Network Interface; Confluent Cloud billing dimensions list no private-networking charge. ↩ ↩2 AWS PrivateLink pricing: $0.01 per endpoint per AZ-hour, data processing $0.01 per GB for the first PB, $0.006 for the next 4 PB, $0.004 above; AWS Transit Gateway pricing: $0.05 per attachment-hour and $0.02 per GB processed, billed to the sender; Amazon MSK pricing: multi-VPC private connectivity $0.006 per GB processed. ↩ Diskless Kafka: KIP-1150 and Kafka’s future, SoftwareMill. The model assumes 4 MB objects at $0.005 per 1,000 writes and every consumer read served from object storage at $0.0004 per 1,000 4 MB reads, with no cache hits (Amazon S3 pricing). ↩ Stanislav Kozlovski, The brutal truth about Apache Kafka cost calculators, December 2024, November 2024 prices; his calculator is AKalculator. ↩ DigitalOcean pricing docs for Droplets, Volumes, Spaces, VPC and Managed Kafka; Akamai Cloud API instance, block and object storage prices; Hetzner Cloud CCX33 and object storage, volumes at €0.0572 per GB-month, converted at $1.15 per euro; OVHcloud multi-AZ. ↩ Apache Kafka 3.9.0 release announcement, November 2024. ↩ Apache Kafka 4.0.0 release announcement, March 2025; Kafka upgrade notes. ↩ Strimzi joins the CNCF incubator, CNCF, February 2024. ↩ Streams Messaging and What’s new in Streams Messaging, 7.3.2, Cloudera documentation. ↩ Manage Confluent Platform licenses, Confluent documentation. ↩ Confluent price list on the UK G-Cloud 15 framework, January 2026: Confluent Platform standard node, Gold $12,000 and Platinum $15,000 per year in production, a node being up to 56 cores, 24 drives, 50 TB and 256 GB of RAM; Cloudera’s pricing page, May 2024: Cloudera Base at $10,000 per node plus $100 per CCU and $25 to $100 per TB; Redpanda licensing. List prices; negotiated prices differ. ↩ Tableflow is generally available, Confluent; Amazon MSK Express brokers deliver data to streaming tables for Apache Iceberg, AWS, July 2026; Iceberg Topics for Apache Kafka, Aiven. ↩ Amazon MSK pricing and the AWS price list for US East, November 2026: Standard kafka.m7g.2xlarge $0.816 per hour, broker storage $0.10 and tiered $0.06 per GB-month, tiered retrieval $0.0015 per GB; Express express.m8g.large $0.3468 per hour, scaling linearly by size, $0.01 per GB written, $0.10 per GB-month; Serverless as stated. Throughput from Amazon MSK quotas: Express sustained 15.6 MB/s in and 31.2 MB/s out per large, Serverless 200 MB/s in and 400 MB/s out per cluster. The model assumes fetch-from-follower on Express, partitions at 2.5 MB/s for Serverless and 5% of reads from tiered storage. ↩ Amazon Managed Service for Apache Flink pricing, US East. ↩ ClickHouse Cloud pricing, Scale tier, AWS US East; ClickPipes also charges $0.20 per compute unit-hour. ↩ For example Redpanda on BYOC and sovereignty and StreamNative BYOC. ↩ Data streaming landscape Q3 2026, Kai Waehner; Confluent describes itself as “an IBM company” in its Streamhouse announcement. ↩ Jha et al., ITBench: Evaluating AI agents across diverse real-world IT automation tasks, ICML 2025. ↩ Jinlang Wang, Jiawei Tyler Gu, Ruize Tang, Tej Chajed, Tianyin Xu and Xudong Sun, Formal operations specifications for reliable system management, HotNets ‘26, doi:10.1145/3847290.3859962. ↩ --- # Kafka at the Edge: Trading Consensus for Compatibility URL: https://platformatory.io/blog/kafka-at-the-edge/ Published: 2026-11-24 Authors: Pavan Keshavamurthy Categories: Kafka, Edge, IoT At Current 2026 in San Francisco on 5 November, my colleague Avinash Upadhyaya took Apache Kafka to the edge in a Meet-Up Hub session: a single-node broker built for unreliable networks, MQTT and HTTP beside it, and local processing to “stream, buffer, aggregate, and forward”.1 The defining property of an edge site is that its uplink fails. A plant on a leased line, a store on consumer broadband, a vehicle on cellular, a vessel on satellite: each loses its connection upstream for minutes, hours or days, and none can promise when it comes back. Everything else about edge streaming follows from that. Every edge architecture is also a decision about the compute continuum, about what runs on the device, on a gateway at the site, and in the cloud. The usual answer puts Kafka at the cloud end and something lighter, usually an MQTT broker and a bridge, everywhere else. We’ve built a different answer: Leafcuttr runs the Kafka protocol at the edge on a single node, speaks MQTT and HTTP beside it, and forwards upstream when the link is up. It gives up the consensus and the parallelism that make Kafka a distributed system and keeps everything that makes it an ecosystem. More than 80% of the Fortune 100 use Apache Kafka, by the project’s own count, and its industry snapshot lists all ten of the ten largest companies in manufacturing, and in energy and utilities, among its users, with eight of ten in transportation and in telecoms.2 Those are the industries with the most sensors, plants, vehicles and networks. Nobody publishes a count of companies running Kafka for IoT specifically, so the honest version of the claim is narrower: in the industries that generate the most edge data, the platform that data is headed for already speaks Kafka. The IoT stack agrees. ThingsBoard, an open-source IoT platform, lists Kafka as the queue for its incoming telemetry, and TBMQ, an MQTT broker, uses Kafka as the storage layer for its sessions and messages.3 Even systems built around MQTT land their data on Kafka, because that’s where the consumers are: stream processors, connectors to warehouses and lakes, schema registries, security tooling, and the people who know how to run them. Every hop that speaks another protocol needs a bridge, and every bridge rebuilds a slice of that ecosystem. Two things make that pull stronger now. The lake has become an extension of the stream: Confluent’s Tableflow materialises Kafka topics as Iceberg or Delta Lake tables, and Redpanda can store a topic’s data as an Iceberg table directly.4 A record that leaves the site in the Kafka protocol reaches the lakehouse with one schema and one lineage, and a record that leaves in another protocol is translated at least once on the way. The second is an assumption we design to, and haven’t surveyed: a site gateway, or a spare slice of an industrial PC, now has room for a JVM broker. Our working budget is half a vCPU and 1 GiB of memory. When the uplink is what fails A site that can’t reach upstream has to hold what it produces until it can. A log is the natural shape for that. Producers keep writing locally at their own pace, and forwarding upstream is one more consumer reading from an offset. When the link drops, the consumer stops. When the link returns, it resumes from its last committed offset, so catching up is a replay of the log with no recovery procedure, and nothing about the producers changes. The arithmetic of an outage is simple. A site producing at rate \(r\) through an outage of length \(t_{\text{out}}\) needs local storage for \(r \times t_{\text{out}}\), and with uplink bandwidth \(B\) it catches up in \[t_{\text{catch}} = \frac{r \, t_{\text{out}}}{B - r}\] because new data keeps arriving while the backlog drains. Backlog at 1 MB/s through an eight-hour outage: 28.8 GB of local disk. Catch-up over a 5 MB/s uplink: 28.8 GB drained at 4 MB/s net, about two hours. The limit: as \(r\) approaches \(B\), catch-up time grows without bound, so a site that can’t send less than it produces never catches up. That last line is why the edge also needs to reduce data before it leaves, which we come back to below. Upstream, the destination is a cloud streaming service that speaks the same protocol. Leafcuttr forwards with an in-process MirrorMaker 2 instance, so the upstream side needs nothing Leafcuttr-specific. Forwarding is marked work in progress in the current release, v0.5.3.5 The obvious objection is that the producer could hold the backlog itself. Stock Kafka clients don’t. The Java producer buffers in memory, 32 MB by default, and fails a record that isn’t delivered within delivery.timeout.ms, two minutes by default. librdkafka’s queue tops out at 100,000 messages or 1 GB and times a message out after five minutes.6 Agents that spill to disk do exist: the OpenTelemetry Collector can put its sending queue in a write-ahead log on disk, and Fluent Bit can buffer in the filesystem.7 For one application with no local readers, whose data only has to get upstream, a producer that spills to disk is simpler than a log beside it, until there’s a second producer: Every client changes. A spilling Kafka producer is a fork of each client you run (Java, librdkafka and the many clients built on it, Go, Rust), each with its own disk format, fsync policy, retry logic and metrics. The buffer is write-only. Nothing at the site can read a spill file until it drains, and the edge has local readers: detection, control loops, and the filtering that shrinks the backlog before it crosses the uplink. Some devices have no disk. Sensors and controllers that speak MQTT can’t spill, so something at the site holds their data anyway. Replays duplicate. The broker deduplicates retries by a producer ID it assigns and a per-message sequence number.8 A producer that restarts and replays its spill gets a new producer ID, so the broker can’t recognise the replay. A forwarder re-sends at most what it sent since its last offset commit. The fsync stays. A spill buffer that survives a power cut pays the same synchronous write as the log, in every application. A sidecar log is that producer-side buffer moved out of the process and behind the protocol, so every client gets it without changing. What sits in the replication path A Kafka cluster earns its complexity with two properties: availability through replication and consensus, and throughput through parallelism across many partitions and brokers. Both run through machinery that’s always on the write path in a cluster. Consensus. A KRaft controller quorum holds the cluster’s metadata, tracks broker liveness through heartbeats, elects partition leaders and records every change to a partition’s in-sync replica set.8 The ISR. Each partition leader tracks which followers are in sync. A follower that hasn’t caught up to the leader’s log end within replica.lag.time.max.ms (30 seconds by default) is removed from the set.9 Follower fetch. Followers pull from the leader continuously, and a message counts as committed only once every in-sync replica has it and the set is at least min.insync.replicas large.8 Purgatory. A produce request with acks=all can’t be answered when the leader appends it, so it’s parked in the request purgatory until the in-sync replicas have fetched it or it times out.10 None of that involves fsync. Kafka writes to the filesystem “without necessarily flushing to disk”, leaving data in the page cache, and its designers rejected an fsync on every write because it “can reduce performance by two to three orders of magnitude”.8 The broker’s log.flush.interval.messages defaults to 263−1, so in practice the kernel decides when data reaches the disk.9 Kafka’s durability comes from copies on other machines. On one node that machinery protects nothing. A single Apache Kafka broker with a replication factor of one skips the waiting, since its in-sync set is just the leader, but it still runs the controller and the replication code, and it still acknowledges from the page cache, so a power cut loses whatever the kernel hadn’t written. Leafcuttr’s isolated mode runs “an optimised code path with replication disabled”, which takes ISR tracking, follower fetch and the produce purgatory off the write path altogether.11 Topic sync then puts the guarantee back where a single node can keep it. Log segments are opened with O_DSYNC, so data is “committed to the physical medium before the producer is acknowledged”; index files still flush on the usual schedule.12 The acknowledgement waits on the local disk, the one dependency an edge site can count on. That disk is often the weakest part of edge hardware. A synchronous write to an SD card or eMMC takes far longer than one to a datacentre SSD, and every one wears the flash. Topic sync is set per topic, lc.log.sync.always, so it belongs on the topics whose loss matters: commands, alarms and events of record. High-rate telemetry that can lose a few seconds in a power cut stays on the page cache and batches. Synced topics need storage rated for their write load, which on most sites means industrial-grade flash. The simplest version of this design needs no new software: one Apache Kafka broker, flush.messages=1 on the topics that matter, and MirrorMaker 2 to forward.13 For a site with hardware to spare and only Kafka clients, that’s good enough. It still costs the controller beside the broker, a second JVM for the schema registry, a separate MQTT broker for the devices that can’t speak Kafka, and a write path built to be replicated, now made to fsync every message. Leafcuttr’s answer is to combine the pieces: the broker, the schema registry and the protocol listeners in one process, so a site runs fewer of them, with replication disabled and topic sync on the topics that need it. We measured that difference on a deliberately small allocation: half a vCPU and 1 GiB of memory on a 2-vCPU host. Apache Kafka 4.0.0 and a separate schema registry shared that budget, 400 and 100 millicores and 512 MiB each, while Leafcuttr runs the broker and the registry in one process and had all of it, so part of the difference comes from running one JVM where Kafka needed two, which is the point of combining them. In the fsync runs Kafka synced every message with the topic setting flush.messages=1, and Leafcuttr used topic sync. One producer wrote 10 KB records to 12 partitions, evolving its schema as it went, three runs per case:14 fsync on, stock producer: 3.55 MB/s for Leafcuttr against 1.96 for Kafka, with average latency of 5.5 seconds against 8.9. fsync on, tuned producer (200 KB batches, 100 ms linger, LZ4): 32.53 MB/s against 23.21, with a p99 of 1.77 seconds against 2.47. tmpfs, stock producer: 87.64 MB/s against 72.1, with a p99 of 411 ms against 753. These are throughput runs, so the multi-second averages in the first row are mostly time records spent queued in the producer’s 32 MB buffer while the disk kept up. The runs cover the write path only. They don’t include an outage and its catch-up, forwarding, data lost in a power cut, or MQTT ingest. A producer could get some availability back without consensus by sending each write to two or more edge brokers and treating the first acknowledgement as success. That’s leaderless replication with a write quorum of one, and it keeps writes flowing while one broker is down. Leaderless Kafka works in the cloud because its brokers share an object store that holds the durable copy. An edge site has no shared store behind its brokers, so a hedged write gives up durability: at the acknowledgement one copy exists, and a broker that fails before the others receive the record takes it with it. It also gives up the single log. Each broker assigns its own offsets, writes from several producers interleave differently on each, and partial failures leave the brokers holding different records, which every consumer pays for: Failing over to another copy needs offset translation or a seek by timestamp, with duplicates or a gap at the switch, because committed offsets mean nothing on the other broker. Reading every copy needs a producer ID and sequence on each record and dedup state in each consumer, kept for as long as the worst outage. Per-producer order can be rebuilt from the sequences; order across producers isn’t defined anywhere. Upstream receives each record once per copy, so the cloud deduplicates too. That’s workable for telemetry keyed by device and timestamp, where per-device order is all that matters and every write is an upsert. Journals are another matter, since there the order is the record. Stock Apache Flink, Connect and Kafka Streams jobs don’t deduplicate across independent logs either, so a swapped-out producer brings swapped-out consumers with it. A site that has to survive a broker failure is better served by two or three brokers replicating over the site’s LAN, where the network is reliable and consensus is cheap. Consensus belongs inside the site, and the uplink is where it stops paying. Speaking the Kafka protocol at the edge is worth the trade only if the rest of the ecosystem comes with it, starting with the contracts and the processing. Schemas. Leafcuttr embeds a schema registry compatible with the Confluent Schema Registry API, stored in a Kafka topic, so producers at the site register and validate schemas offline with the same serializers they’d use against the cloud.15 Processing. Leafcuttr v1.0, the next major release, will add filters, joins and functional operators over local topics, so a site can drop noise, enrich readings with local reference data and aggregate before anything crosses the uplink.16 On a flaky or metered link, every byte filtered locally is a byte that never sits in the backlog. Other protocols. MQTT 3 and 5 and HTTP are accepted in the same process, with MQTT topics mapped to Kafka topics, so devices that can’t speak Kafka still land in a Kafka log without a separate broker or bridge.17 The alternative to a log at the edge is the familiar stack: an MQTT broker at the site, a bridge that consumes from it and produces to Kafka, and Kafka somewhere upstream. MQTT is good at what it does, and devices that can only speak it should keep speaking it. The extra layers still cost something. Compute. In an independent benchmark of eight brokers on edge-sized machines, Mosquitto used 284 to 620 MB under load, HiveMQ 487 MB to 1.7 GB and EMQX 650 MB to 3.7 GB.18 A Kafka Connect worker’s start-up script gives it a heap of up to 2 GB by default.19 Mosquitto’s measured memory plus the bridge’s default heap ceiling comes to roughly 2.3 to 2.6 GB across two runtimes. Leafcuttr ran in our benchmark with 1 GiB. Durability. An MQTT QoS 1 acknowledgement means the broker has the message, which may still be only in memory. Mosquitto’s persistence is off by default, and when it’s on it saves every 1,800 seconds by default.20 If the bridge stops consuming while upstream is down, the backlog queues in the broker, and a crash between saves loses up to \(r \times t_{\text{save}}\), 1.8 GB at 1 MB/s. EMQX 5.x’s own Kafka integration can buffer on disk, which survives a node restart; in memory mode the buffer is lost on a restart.21 Latency. The broker hop is fast, with median latency of 0.21 to 0.76 ms for 1 KB messages.18 The bridge then batches like any producer, and since Kafka 4.0 a producer waits up to 5 ms by default to fill a batch.22 Tuning narrows the gap. Mosquitto with persistence on and a short autosave interval shrinks the window of loss,20 and a broker with its own Kafka integration, such as EMQX, replaces the Connect worker and most of its memory, with a disk buffer when it’s configured.21 What tuning doesn’t remove is the second protocol hop, a second store to size and watch, and the gap at the site itself: no Kafka clients, no schema registry and no local consumer reading the backlog in the protocol the cloud speaks. The durability line matters most for the main problem. During an outage, the bridged path holds the backlog in a broker and a bridge buffer, and each persists only if someone configured it to. Store-and-forward at the edge is an old idea, and the closest design to this one comes from NATS. A NATS leaf node is a NATS server at the site that dials out to a hub and bridges subject interest across the link. It can run its own JetStream store in a separate domain, so the site’s streams stay apart from the hub’s, with streams mirrored or sourced between the two.23 It’s a mature design, and where the cloud side isn’t Kafka, it’s the better choice. Where the cloud side is Kafka, a leaf node is one more protocol at the boundary: the site’s data still crosses a bridge to reach the stream processors, connectors and schema registry upstream, and nothing at the site speaks the protocol those tools expect. Sidecars and journals A site gateway fans in many devices. The other shape on the continuum is one log per workload, running beside it as a sidecar on the same host or in the same pod. Leafcuttr runs either way.24 Streaming sidecar. An application that already produces to Kafka keeps its client and its code. A network filter redirects its Kafka traffic to the local sidecar, or injected configuration points bootstrap.servers at localhost, so the application writes to a log on its own host and the sidecar forwards upstream when the link allows. The producer sees a local broker that’s always there, and an outage becomes backlog: the application sees no produce errors or retry storms. Journal sidecar. An autonomous system, such as a robot, a vehicle controller or an agent, records what it saw, decided and did in a local log beside it. The journal is the audit trail while the system is offline and replays upstream when it reconnects, in order, with the same schemas the cloud consumers expect.24 Because the routing happens in the network or in injected configuration, sidecars can be rolled out the way a service mesh is, with no change to application code. Giving up consensus is the right call when the edge node’s job is to capture, hold, shape and forward, and the system of record is upstream: Telemetry and store-and-forward from plants, stores, vehicles and robots, where outages are routine and a delay is acceptable but a gap isn’t. Bounded-time detection on network flows or sensor data, where a local consumer has to act before the cloud could. Agent and machine journals that must survive the time they spend offline. Feature and training capture for models trained centrally on edge data. It’s the wrong call when the edge node is itself the system of record and must stay available through its own failure (replication and consensus exist for that, and the cloud should own it), when one site’s throughput needs many brokers, or when the device is too small to run a broker at all. Those devices keep speaking MQTT, to a log that accepts it. For a site already on MQTT, that’s the migration: the devices stay as they are, point at the log’s MQTT listener, and the bridge goes. Two signals would show this is the wrong default. One is MQTT brokers shipping Kafka-protocol egress with a durable disk buffer turned on out of the box, which would close most of the durability gap and remove the separate bridge. The other is catch-up limited in practice by the cloud side, by ingest quotas or upstream consumer lag, more than by the uplink, which would make a fast local replay matter less than the arithmetic says. Current 2026 San Francisco: Taking Apache Kafka to the Edge, Meet-Up Hub session, 5 November 2026. ↩ Apache Kafka, project home page, read November 2026. ↩ Apache Kafka: Powered By. ↩ Confluent Cloud: Tableflow overview, “materializes Apache Kafka topics as Apache Iceberg or Delta Lake tables”; Redpanda: About Iceberg topics, v26.3, an enterprise-licensed feature. ↩ Leafcuttr documentation, Topic forwarding, v0.5.3: lc.topic.forward.config points at a MirrorMaker 2 configuration; the feature is marked work in progress. ↩ Apache Kafka 4.1 producer configs: buffer.memory 33554432, delivery.timeout.ms 120000; librdkafka CONFIGURATION.md: queue.buffering.max.messages 100000, queue.buffering.max.kbytes 1048576, message.timeout.ms 300000. ↩ OpenTelemetry Collector: resiliency, persistent sending queue with the file_storage extension; Fluent Bit: buffering and storage. ↩ Apache Kafka 4.1 documentation: Design, sections on persistence and replication. ↩ ↩2 ↩3 ↩4 Apache Kafka 4.1 documentation: Broker configs: replica.lag.time.max.ms default 30000; log.flush.interval.messages and log.flush.scheduler.interval.ms default 9223372036854775807. ↩ ↩2 Yasuhiro Matsuda, Apache Kafka, Purgatory, and Hierarchical Timing Wheels, October 2015; the mechanism is unchanged in Kafka 4.1. ↩ Leafcuttr: Isolated mode, documentation v0.5.3. ↩ Leafcuttr: Topic sync mode. ↩ Apache Kafka 4.1 documentation: Topic configs: flush.messages “allows specifying an interval at which we will force an fsync of data written to the log”; 1 forces an fsync after every message. ↩ Our own benchmark, summarised at Leafcuttr benchmarks: apache/kafka:4.0.0 at 400m CPU, 512 MiB and a 460 MB heap plus a schema registry at 100m and 512 MiB, against Leafcuttr lc-0.4 at 500m, 1 GiB and a 920 MB heap, on a 2-vCPU, 8 GB host; 10,000-byte records, 12 partitions, one producer; Kafka fsync rows with topic flush.messages=1; averages of three runs. ↩ Leafcuttr: Schema registry: lc.schema.registry.enable, default port 8081, schemas stored in the _schemas topic; Avro is the primary format. ↩ Leafcuttr features: filtering, forwarding and aggregation listed as coming in v1.0. ↩ Leafcuttr: MQTT broker and proxy; MQTT 3 and 5. ↩ Paul et al., Benchmarking message brokers for IoT edge computing, March 2026: eight brokers (Kafka not among them) on 1, 2 and 4 vCPU virtual machines; memory under load and median latency for 1 KB messages on 4 vCPUs. ↩ ↩2 bin/connect-distributed.sh: -Xms256M -Xmx2G when no heap is set; bin/kafka-server-start.sh gives a broker -Xmx1G -Xms1G. ↩ mosquitto.conf(5): persistence defaults to false; autosave_interval defaults to 1,800 seconds. ↩ ↩2 EMQX: Stream MQTT data into Apache Kafka, buffer mode: memory, disk or hybrid; disk survives a node restart, memory doesn’t. ↩ ↩2 KIP-1030: linger.ms default raised from 0 to 5 in 4.0. ↩ NATS documentation: Leaf nodes, including JetStream domains over a leaf and mirrors and sources across it. ↩ Leafcuttr deployment modes: gateway, sidecar or embedded, and agent journal. ↩ ↩2 --- # Securing AI Agents: Zero-Trust Identity and Authorization for MCP and A2A URL: https://platformatory.io/blog/identity-for-ai-agents/ Published: 2026-11-24 Authors: Pavan Keshavamurthy Categories: Security, AI, Platform Engineering, API Management An agent that calls an API on someone’s behalf brings back a question OAuth answered for web apps fifteen years ago: whose authority is being exercised? For web apps, a registered client acted for a signed-in user, one hop from the API. An agent’s request is a chain. A person delegates to an agent product, a running instance of it decides to call a tool, the tool’s server calls an API, and the agent may hand part of the job to another agent that does the same. At every hop the receiver has to establish four things from what arrives: which software sent it, which instance, on whose behalf, and with how much of that party’s authority. Agents change one thing: all four must survive every hop, for a caller that chooses its own next action and reads untrusted text while it does. Four failures follow from getting it wrong. Norm Hardy named the first in 1988: a confused deputy uses its own authority for someone who shouldn’t have it.1 The second is a stolen or replayed token, used by someone it wasn’t issued to. In the third, authority grows as it moves, and a sub-agent, a tool server or a gateway ends up able to do more than the person at the top of the chain could. The fourth is the oldest: an insider, a person or now an agent, misusing access they legitimately hold. Zero trust’s answer, deciding every request as if the network were compromised, catches much of the first three. It doesn’t catch an agent that passes every check while doing an attacker’s work, or a person who controls the checks. Who is calling Which software? Registration answers this, and for agents it has settled quickly. MCP first adopted Dynamic Client Registration (RFC 7591) because a client meets servers it has never seen,2 and it went badly at scale: clients registered a new client_id at every login, and servers needed rate limiting against unbounded growth.3 The MCP revision of 28 July 2026 deprecated DCR in favour of Client ID Metadata Documents.4 With them, the client_id is an HTTPS URL, the authorization server fetches the client’s metadata from it, and trust in the client becomes trust in whoever controls that DNS name. Most identity providers now accept metadata documents.5 Microsoft Entra ID added them in public preview in October 2026, representing each such client as an agent identity in the tenant, with narrow limits: user-present delegated flows only, no client credentials grant, no confidential-client authentication, and narrow default scopes, with pre-registration still the recommended path.6 A confidential agent on Entra is pre-registered or sits behind a broker that acts as the authorization server for MCP, which quietly moves part of identity into whatever that broker is. Doesn’t the metadata document already give the client a key? It can. The document is public, so the draft that defines it forbids shared secrets but allows public keys, inline as jwks or by reference as jwks_uri, for private_key_jwt.7 That proves the caller holds a key the publisher vouched for, and says nothing about which running copy holds it. In the simplest deployment every instance shares one private key, readable by anything that can read the deployment’s secrets, an agent talked into printing its environment included. Which instance? One product runs as many workloads, each serving many sessions. Workload identity tells the workloads apart, as it already does for services, and tokens carry the session. SPIFFE gives each workload an identity document, an SVID, as an X.509 certificate for mutual TLS or as a signed JWT. SPIRE, its reference implementation, issues one only after checking where the workload runs, its node, pod or process, and by default a certificate is valid for an hour and a JWT for five minutes, renewed automatically, so there’s no long-lived key to copy.8 How do the two fit together? An OAuth working-group draft composes them: a metadata document can declare a spiffe_id pattern for the workloads that may authenticate as the client and a spiffe_bundle_endpoint for the keys that verify them.9 What that proves depends on where the bundle comes from. Fetched from the document, it proves only that whoever controls the client_id URL vouches for the key; the SVID proves which instance is calling only to a server that trusts the SPIFFE trust domain out of band. And a JWT-SVID works for anyone who copies it until it expires, while an X.509 SVID over mutual TLS proves possession of a key that instance alone holds. Most agents in production use neither. A local MCP server launched over standard input and output takes its credentials from the environment instead of running OAuth, which in practice means an API key in a variable.10 Agents on a hyperscaler get their instance identity from the cloud’s own workload identity, which does SPIFFE’s job inside one provider.11 Agents that drive a browser are only starting to sign their requests, and then only to say which operator’s bot is calling.12 The further an estate is from an OAuth-speaking client, the more of the work falls to the traffic plane. On whose behalf? Services never had to track this party: the user. A user delegates to an agent through the authorization code flow with PKCE, and the resulting token’s subject is the user and its client is the agent. In an enterprise, asking every user to consent to every MCP server is unworkable, so the identity provider exchanges the user’s single sign-on token for an identity assertion that the downstream authorization server accepts instead. The draft, informally Cross-App Access, is in the OAuth working group, MCP carries it as an extension, and Okta’s Agent SSO implements it.1314 Delegation itself is data. OAuth Token Exchange (RFC 8693) records in an act claim that one party is acting for another, nests act claims to express a chain, and uses may_act to say in advance which parties may act for a subject,15 so a token can say “the user, via this agent, via this tool server”. Consumers decide on the top-level claims and the current actor, the nested chain is for audit, and any narrowing it implies has to be done by the authorization server that issued each token. Tokens that only work where they’re meant to An MCP server is an OAuth resource server. The client names the server it wants a token for with a resource indicator (RFC 8707), and the server rejects any token not issued for it.4 That audience binding is what stops a token issued for a low-risk tool being replayed against a high-risk one. Why can’t a tool server pass the token along? Because it would become a confused deputy for every caller. An MCP server “MUST NOT pass through the token it received” to an upstream API; the upstream token is a separate one, from the upstream’s authorization server.16 How the server gets it depends on who runs that authorization server. Inside your own domain: token exchange, with the user as subject and the tool server as current actor. RFC 8693 doesn’t require the result to be narrower, so the authorization server has to refuse anything wider. Across domains that trust each other: identity chaining or an identity assertion grant.17 Third-party SaaS with no trust relationship, the GitHub, Salesforce or Google APIs most tools wrap: a separate grant per user per upstream, which makes the tool server, or the gateway in front of it, a store of users’ upstream refresh tokens. Most deployments are here, and it’s where the confused deputy actually lives. What stops a stolen token being used? Nothing, if it’s a bearer token, and agents are unusually good at leaking them. Certificate-bound tokens over mutual TLS (RFC 8705) and DPoP, which signs each request with a key whose thumbprint is in the token (RFC 9449), bind a token to a key the holder must prove it has.18 Both work only if the key lives outside the model, in the runtime or a sidecar that attaches credentials to outbound calls. The model chooses actions, and something it can’t read holds the keys. Binding stops theft and replay. It doesn’t stop an injected instruction from getting the runtime to make a correctly signed call, which is what authorizing the call’s arguments is for. Lifetimes measured in minutes are what make theft survivable, and agent tasks run for hours. The runtime refreshes or re-exchanges on the agent’s behalf, which keeps the access token’s window short and makes the refresh token the long-lived credential in the system. Where one is issued, it should be sender-constrained or rotated on use, and it’s what revocation has to reach. Authorization: from scopes to task-bounded authority A scope can’t bound an agent as tightly as its task requires. A token without the scopes an operation requires gets a 403 with error="insufficient_scope", and the client can come back for more, a step-up.4 But orders:write can’t express “refunds up to $500, on this customer’s orders, while this support ticket is open”. Rich Authorization Requests (RFC 9396) can: an authorization_details parameter carries typed JSON objects naming actions, locations, data types and fields such as an amount or an identifier, and the authorization server returns what it granted.19 Payments got there first: the Agent Payments Protocol’s mandates are signed credentials recording a user’s constraints for a purchase,20 task-bounded authority with a merchant at the end of it. Outside payments, task-scoped authority is rarely used for agents yet. Why must the server authorize arguments as well as callers? Because the arguments come from a model that may have just read a hostile web page, email or document. Prompt injection turns the agent itself into a confused deputy: it holds the user’s authority and acts on an attacker’s instructions. Authenticating the caller can’t detect that, since the caller is genuine. What limits it is checking each request against what the task needs, so an agent working a refund ticket can’t be talked into exporting the customer table even though the user could. An agent’s effective permission is the intersection of what the user may do, what the agent may do, and what the task requires. Tokens carry the first two as subject, client and scopes. The third is what Rich Authorization Requests and policy have to supply, and today it mostly lives in application code. Each of the four access models in common use covers part of it: Model Decides on Fits agents for Strains when Role-based (RBAC) Fixed roles mapped to permissions Admission: which tools an agent can see at all Roles multiply per agent, task and tenant Attribute-based (ABAC) Attributes of caller, resource, action and environment Runtime facts: the delegating user, the task, the budget left, whether input came from an untrusted source Policies get hard to audit without a language for them Relationship-based (ReBAC) Relationships in a graph, as in Google’s Zanzibar21 Data access when the agent acts for a user who can see some documents and not others The relationship graph has to stay current Policy-based (PBAC) Policies as code in a decision service, such as OPA’s Rego or Cedar22 Managing all of the above: one policy, reviewed like code, evaluated everywhere An operating model, usually over attributes; needs a team to own it Agents push toward attributes and policy because the facts that decide a request exist only at runtime, and the task, the most important of them, is native to none of the four. Roles can’t keep up. With an illustrative 50 agents, 20 task types and 30 tenants, \[R = a \times t \times n = 50 \times 20 \times 30 = 30{,}000\] That’s thirty thousand role bindings to review, where a policy parameterised on agent, task and tenant is one rule. Policy-based control is how the other three are run at scale: as code in one repository, reviewed, tested and evaluated by a decision service. The choice of engine is still open. OPA is the established general-purpose one, and Cedar, already applied to chains of agents,23 was designed to be analysable, so a tool can prove what a policy forbids,24 which matters when the question is what an agent can’t do. What should the tree of agents carry? An orchestrator that spawns sub-agents builds a tree, and the question is where a sub-agent’s authority comes from. Three answers are in use. The tree carries permissions. A child inherits its parent’s access, or, in the org-chart version, a supervising agent inherits everything its children can reach. It needs the least administration and matches how orchestrators work. It also gives every child everything whatever its sub-task and gathers privilege at the top: authority grows as it moves, by design. The tree carries ownership only. Each agent’s permissions come straight from policy, and the tree records who is accountable for whom. It’s simple and auditable, and a sub-agent can hold more authority than the agent that started it. The tree carries delegation and ownership. Central policy sets each agent’s ceiling, what that kind of agent could ever do. Delegation can only narrow it: a child’s authority is its own ceiling intersected with what its parent hands down for the sub-task, a subset of scopes, a smaller budget and a shorter lifetime at each level. It costs a token exchange per hop, an authorization server that refuses to widen, and a sub-task described well enough to narrow. We take the third, and owning an agent then means controlling it without inheriting what it can reach. It’s the property capability systems were built on and macaroons made portable, where anyone holding a credential can add caveats and nobody can remove them.25 Token exchange delivers it if the authorization server enforces the intersection at every exchange. Each token’s top-level scopes and authorization details are then the intersection, so every consumer, the traffic plane included, enforces them like any other claim, and the nested act chain records how they got there. Ownership is a different kind of authority: authority over an agent, to inspect it, pause it, cancel it or revoke it, held by its parent and its human owner. It also carries accountability, every agent traced to a person and a sponsoring team, and keeping it separate from delegation stops a supervising agent collecting everything below it. Agents with no parent, a scheduled job with no user behind it, get standing grants from policy, at the ceiling and no higher. In the Agent2Agent protocol (version 1.0), an agent’s Agent Card declares the security schemes a caller must satisfy and can be signed. Authorization is left to the implementation, and an agent that needs more authority mid-task moves the task to TASK_STATE_AUTH_REQUIRED and receives it out of band.26 An A2A agent decides what to do, may delegate further and may run for hours, so the intersection of user, agent and task has to be re-evaluated at every hop, and the task description has to travel with the request. Inside one trust domain, transaction tokens carry it: a signed JWT minted at the edge for one call chain, lasting minutes or less, never usable as an access token, whose scope captures the transaction’s purpose “as narrowly as possible” and whose context no replacement may expand.27 Across domains, what’s left is identity chaining and assertion grants between authorization servers that trust each other, which works where organisations have set it up and nowhere else. Who governs the policy An auditor’s first question about agents is which agents can reach this system, for whom, and under what conditions, and in most estates nobody can answer it, because the rules are written separately in each service. They cut across every service: which agents may reach which tools and APIs, how authority narrows as it’s delegated, what a task may touch, how much budget it may spend, which data may leave through a model call, and which actions need a human. Written by each team, the same rule exists a hundred times, a little different each time. Suppose each copy has a small chance \(p\) of being looser than intended, independently of the others. Across \(n\) services the chance that at least one is looser is \[1 - (1-p)^{n} = 1 - 0.98^{100} \approx 0.87\] for an illustrative 2% per copy and a hundred services. An attacker needs only that one. A central policy fails differently: one wrong rule is wrong everywhere at once, so it has to be reviewable and testable in a way a hundred copies never are. The case for leaving authorization in the services is real, and it’s why the last generation of systems was built that way. A service knows its data, its tenants and its edge cases; its team ships rule changes without waiting on anyone; and there’s no central gateway to fail, slow every call, or be compromised once for everyone. It’s more autonomous. It’s also notoriously more difficult to govern, and agents make it harder, because they’re new callers arriving at every service at once with authority that has to be narrowed consistently everywhere. The alternative is enforcement in the traffic plane, the one place every model and tool call can be made to cross. A gateway there can authenticate, exchange tokens, hold the tool allowlist, evaluate policy against the token’s claims and the call’s arguments, meter budgets, filter data on the way out, and keep one audit log that covers third-party tools nobody can change. Where it also acts as the authorization server, it should still mint tokens whose audience is each upstream server, since a single gateway audience recreates the replay problem resource indicators solve. That’s the architecture NIST’s zero-trust standard describes: a policy decision point, enforcement points in the path of every request, and least-privilege access decided per request “in the face of a network viewed as compromised”.28 Two parts of it matter for agents. An enforcement point can’t apply policy beyond its place in the flow, so zero trust moves enforcement as close to the resource as it can: the services behind the gateway trust only a gateway-minted token and check again against the same decision point. And zero trust decides whether a subject may make a request, a test a prompt-injected agent passes: it’s authenticated, authorized and inside policy while doing an attacker’s work. An attacker who can “induce or coerce” a software agent into a task the attacker isn’t privileged to perform is already in the standard’s threat model.28 Task-bounded authority is what agents add on top. Central enforcement comes with a precondition. The traffic plane governs only traffic that crosses it, so services have to accept agent calls only through it, enforced by network policy and by rejecting tokens the gateway didn’t mint, or the central policy is advisory. The design starts with agents because that’s where authority multiplies fastest, and none of it depends on the caller being one: batch jobs, human front ends and service-to-service calls can cross the same plane under the same policy, so an estate that brings them over governs one system where it would otherwise run two. It also makes the gateway’s own credentials the most valuable in the estate, and if it fronts third-party APIs, the vault for users’ upstream refresh tokens too. Those need the narrowest scopes and shortest lifetimes of anything there, or the gateway becomes the confused deputy it exists to prevent. That leaves the rules that depend on data. Whether this user’s agent may read invoice 123 depends on who owns invoice 123, and that used to settle the debate in the services’ favour. The price was authorization rules inside domain code, polluting the domain and repeated as boilerplate in every service. Agents change the trade-off, because a tool call is more legible to a gateway than a REST call ever was: it names the tool and carries typed arguments against a declared JSON Schema,29 so the action, and often the resource, is explicit in the request. Three models are in use for deciding on it centrally, and they differ in where the data lives. A central relationship store. Applications write relationships such as “user A owns invoice 123” into one authorization system, and any enforcement point asks it. That’s Zanzibar’s model,21 and AuthZed’s SpiceDB and the CNCF’s OpenFGA are open-source systems built on it; a gateway can consult one on every request, through Envoy’s external authorization filter for example.30 The cost is keeping the copy fresh. A check against stale relationships admits the user whose access was just removed, Zanzibar’s “new enemy” problem, and SpiceDB’s default check mode, for one, tolerates that window. Its fix, a consistency token stored with the resource, lives in the service’s database, where the gateway never sees it.31 The relationships are data, so a policy review and Cedar’s analysis, which reasons over policies for any data they might meet,24 cover the rules and not the grants. The store should let each service write relationships only for its own resource types, and audit every write. Central policy, data from the request. The policy decides from the token, the tool and its arguments, plus attributes fetched at request time. It’s what AWS ships for agents: AgentCore’s gateway evaluates Cedar on every tool call, with the principal from the token, an action per tool, and conditions on arguments such as an amount below a limit.32 It needs no copy of the data, and it can’t decide anything the request doesn’t reveal. Central policy, local data. The policy is written once and compiled against the service’s own database. OPA’s partial evaluation turns it into a SQL condition, and Oso’s local authorization generates the query from a schema without reading the data.33 Nothing is copied, and the cost moves into the service: someone maps the policy’s facts to its tables, and only some databases are supported. All three keep one owner for the rules, as code, out of domain code. They differ in how much the gateway can decide. With a relationship store it can decide data-level rules for any resource a call names. With request data it decides what the arguments and fetched attributes show, an amount or a tenant, and no more. With local data, a decision about a record is made against the service’s database, so the gateway keeps the coarse rules and the service runs the rest through the platform library. In every model, a tool that picks its own target, “the latest order” or a search, acts on objects the gateway never saw, and its server has to check access regardless.29 Lists are the same case. A gateway can’t filter a database query without breaking pagination and counts, so the decision point returns the allowed identifiers, practical in SpiceDB below about ten thousand per user, or the service checks each page of candidates in bulk, or applies a compiled condition.33 Whether a tool names its target is partly a platform’s choice. It can require tools to name the resource they act on in typed arguments, an invoice_id where a free-text query would do, and treat generic tools such as run_sql, http_request or code execution as guardrail-only: admitted for a task and metered, never trusted to carry a data-level decision. Rules about state are a different kind of rule. Take an agent acting for Alice, a support engineer, on a ticket about order 123, asking to refund $300. The gateway sees the token, the tool and its arguments, and decides who may attempt the refund: this agent may refund on Alice’s behalf, Alice may act on order 123, and $300 is inside the task’s $500. The service decides, when it acts, what only its data shows: the order hasn’t shipped, $300 is no more than the remaining balance, and the ticket hasn’t already had a refund. The first is authorization and belongs to the policy; the second is the domain’s invariants and stays in the domain. Neither check can do the other’s job. Where relationships are fed from events or change data capture, revocations go to the decision point directly and sensitive actions are checked at full consistency, at a cost in latency, because a pipeline’s lag is the window an attacker needs. Five places end up enforcing something, and each is blind to something the others see: Enforcement point Enforces Can’t see Traffic-plane gateway Identity and token exchange; the tool allowlist; guardrail and domain policy on token claims and arguments, including data-level rules where the decision point holds the data; budgets and rate limits; data leaving through model calls; the audit log Resources a tool resolves itself; which rows a list returns; anything that bypasses it Agent runtime Keys held outside the model; proof-of-possession on every call; the sandbox and its network egress; task context attached to outbound calls Whether the next hop honours the task; another runtime’s behaviour Tool server Token audience and issuer; no passthrough; the right grant for the next hop; step-up when scopes fall short The user’s wider intent; calls that don’t reach it Service The same policy, from the same decision point through the platform library, for every resource it touches, including those it resolves itself and lists; its own invariants; only gateway-minted tokens The rest of the chain, except what tokens and transaction context carry Receiving agent Its own Agent Card schemes; authorization of the skill and task; pausing for credentials or a human How the caller’s authority was obtained, beyond the tokens presented Where should a tool call’s arguments be checked? Two placements are defensible, and each buys something the other can’t. In the agent runtime, before the call leaves. The runtime has the full context, including which input was untrusted. It can stop a bad call before any credential is used and ask the user to confirm in place. But it runs beside the model it’s checking, so a compromised agent can skip it, and nobody outside the agent can prove it ran. In the traffic plane, as the call crosses. The gateway applies the same policy to every agent, records the decision in one audit log, and can’t be skipped by the agent it governs. It sees the token, the task carried with the call and the arguments, and none of the reasoning behind them, so its checks are only as good as the task context the runtime attaches. From a platform-engineering point of view, the deciding check belongs in the traffic plane: the one whose denial is final and that the agent can’t skip. It isn’t the only check. Services ask the same decision point again through the platform library, for the resources a call names as well as the ones the gateway can’t see, so a call that slips past the gateway meets the same policy. What the gateway adds is one policy applied the same way to every agent, one audit log, and bad calls stopped before they reach anything. Security has never been a stronger cross-cutting concern than it is with agents, and cross-cutting concerns are best handled once, in the platform tier, where they’re uniform, auditable and outside the reach of the thing they constrain. The arrangement is one policy repository and one decision point, offered as a self-service part of the platform. Security operations writes the guardrails as forbid policies. In Cedar a forbid overrides any permit, so a team’s policy can’t loosen one, but a policy that errors is skipped, so guardrails are validated against a schema before they land, which stops them failing on a missing attribute or a type mismatch.34 Domain teams write the policies for their own resources inside them, own the mapping from each tool’s arguments to the resources they name, versioned with the tool’s schema and checked against its inputSchema in CI so the two can’t drift, and choose a data model per domain: request data where the arguments say enough, a relationship store where access is a graph, local data where the service holds large result sets. Gateways built for model traffic and for tool traffic are converging on this role.35 We build agentic systems, platforms and the event pipelines behind them for customers, so we have a stake in where this layer ends up. Insiders, detection and response Zero trust treats the network as compromised. Agents ask for the same assumption about the people and software inside it, and insider risk takes four shapes. The agent as insider. An authorized agent acting on injected instructions is an insider with its user’s authority. Varonis showed a chain in Microsoft 365 Copilot’s enterprise search that turned the assistant into a way to exfiltrate data, fixed as CVE-2026-42824.36 Task-bounded authority and argument checks are the controls. A person with an agent. An employee who wants data out gets a fast, tireless helper. The intersection caps it, since an agent’s ceiling is narrower than its user’s, and the gateway meters and filters what leaves through model and tool calls. Shadow AI and AI agents now amplify insider risk, and adoption is outrunning visibility.37 Agents nobody registered. A script with an API key or an assistant wired to a mailbox is shadow IT, and zero trust already requires cataloguing it.28 Inventory, and rejecting tokens the gateway didn’t mint, are the controls. The insider in the control plane. Centralising policy puts the most valuable access in the estate in a few hands: whoever can merge to the policy repository, write relationships to the decision point, operate the gateway or edit its audit log. One malicious change is wrong everywhere at once, and a grant written as a relationship is data, so it never passes policy review. The policy management tool should be reachable only from dedicated administrator accounts with the most restrictive access policies.28 For agents that extends to two-person review and signed commits for policy, relationship writes audited like policy changes, different people as policy authors, gateway operators and audit owners, an audit log the gateway’s administrators can’t alter, and break-glass access that pages someone. Detection runs on shared context. Every call carries the user, agent, instance and task, so the gateway’s, runtime’s and services’ records join up, and an agent’s behaviour can be checked against what its task allows. Response has to reach every credential in the chain. Short lifetimes bound the damage but don’t stop a runtime that keeps refreshing, and it’s the refresh tokens, in runtimes and in gateways’ vaults, that have to die. The Shared Signals Framework and its Continuous Access Evaluation Profile, final OpenID specifications since 2025, let an identity provider push events such as a revoked session to the services that rely on it.38 Built for people’s sessions, they need every agent runtime that refreshes or exchanges tokens to subscribe and act, and nothing yet coordinates that across a chain. Response is reaching the host as well. Shirudo, a pre-release open-source runtime from Cisco and OpenAI, lets an agent write signed eBPF or JVM shields that block a vulnerable code path until a patch lands, served from the operator’s own registry and pulled by every host about once a minute by default.39 An agent writing kernel code that a fleet loads within a minute is a control plane in its own right, and its failure mode is on record: a CrowdStrike content update interpreted by its kernel driver hit an estimated 8.5 million Windows machines in July 2024.40 Shields need the policy repository’s two-person review, staged rollout and audit. Where a workload can be air-gapped, the air-gap comes first, with shields inside it for what’s still reachable; agentic streaming has more on the trade. Two controls bound the blast radius when detection is late. Irreversible actions need a fresh grant from the root principal, with the authorization server prompting a human; MCP’s step-up and A2A’s auth-required state give that a place in the protocol, and since step-up widens a token, it’s an approval only if someone is actually asked. Budgets come down the same tree as delegation, as quotas for the organisation, team, agent and task, metered by the gateway: authority expressed as a quantity, divided on the way down and never enlarged. Where the design loses The design assumes most agent traffic is yours to route and its control plane is yours to guard. It loses where that isn’t true: Agents live on someone else’s platform. If most agent work runs inside SaaS agent products, the calls never cross your traffic plane, and the vendor’s admin plane is the enforcement point whether you like it or not. Cross-domain calls dominate. Past the trust boundary the gateway enforces only what leaves; the rest is the other side’s policy and whatever grants the two authorization servers share. The gateway becomes the constraint. A hop on every call costs latency and availability. Where it can’t be made cheap and redundant, teams will route around it, and central policy becomes advisory. The control plane can’t be guarded. An estate that can’t separate and watch the duties around its policy has built a single point of compromise. Two signals would show the position is wrong. One is freshness: if the lag between a revocation and the decision point seeing it regularly outlasts a token’s lifetime, the window short-lived tokens were meant to bound, and the audit log shows calls admitted after access was removed, data-level checks belong back where the data is. The other is the shape of the traffic: if most agent calls in the gateway’s audit log are searches and listings rather than actions on named resources, most real enforcement happens in the platform library inside services, and the gateway is left with the coarse guardrails. Where to start Most estates are at the shared-service-account stage. In this order, each step either removes the biggest risk left or is what the next one needs, and each costs something: Inventory agent identities. List every agent, the credentials it holds and the human who sponsors it. It costs a few weeks of reading configs and answers the auditor’s question. Stop token passthrough. Use token exchange inside the domain and separate grants for third-party APIs. The cost is a token vault that needs the same care as signing keys. Route agent and tool traffic through one gateway, and reject tokens it didn’t mint. This is the expensive step: network policy, a migration per service, and a component that has to be as available as the identity provider. Move cross-cutting rules into one policy repository. Allowlists, delegation limits, budgets and egress rules go there, as guardrails. It needs a team that owns it and a review queue every rule change waits in. Guard the control plane. Do it as soon as the repository exists: two-person review for policy, audited relationship writes, separated duties and an audit log its operators can’t edit. It costs reviewers and a slower path for every change. Put domain policy in the platform. Domain teams write policies for their own resources in the same repository, inside the guardrails, with a data model per domain. Require tools to name their target resource in typed arguments, and keep generic tools guardrail-only. It costs a mapping from tool arguments to resources kept in step with each tool’s schema, a platform library in every service that resolves its own targets, and for a relationship store, a pipeline that keeps it fresh. Give each instance its own identity and keep keys out of the model’s reach. Use SPIFFE where you run the infrastructure, the cloud’s workload identity where you don’t, and DPoP for clients that can’t hold a trusted key. SPIRE is the costly part: attestation, federation and a team that keeps it running. ProTip: Start the inventory with the agents nobody launched on purpose: the scheduled jobs and the scripts with an API key in an environment variable. They hold standing authority, and no consent screen ever showed them to anyone. Task scope has no standard yet. Nothing says how a task’s description becomes authorization_details, who writes it, or how it’s issued outside the agent runtime, which the gateway has to trust today. Inside one estate, most of these questions come down to where the rules live, whether every agent call has to pass the place that enforces them, and who is allowed to change it. Between estates, they come down to what two authorization servers agree to trust, and that’s where the next round of standards work will be. Norm Hardy, The Confused Deputy (or why capabilities might have been invented), ACM SIGOPS Operating Systems Review 22(4), October 1988. ↩ RFC 7591: OAuth 2.0 Dynamic Client Registration Protocol, July 2015. ↩ Aaron Parecki, Client registration and enterprise management in the November 2025 MCP authorization spec, 25 November 2025. ↩ Model Context Protocol: Authorization, specification version 2026-07-28; the 2025-11-25 version first preferred Client ID Metadata Documents. ↩ ↩2 ↩3 Okta, Auth0, WorkOS and Clerk accept them, and Keycloak behind an experimental flag: Okta: register AI agents with a CIMD; Auth0: register applications with CIMD; WorkOS changelog, 30 November 2025; Clerk changelog, September 2026; Keycloak: integrating with MCP. ↩ Microsoft, Client ID Metadata Documents in Microsoft Entra ID (public preview), 30 October 2026. ↩ draft-ietf-oauth-client-id-metadata-document, OAuth working group, revision 03, sections 4.1 and 10.3. MCP 2026-07-28 references revision 00, whose section 4.1 carries the same prohibition. ↩ SPIFFE overview; SPIRE server configuration (default_x509_svid_ttl one hour, default_jwt_svid_ttl five minutes). Attestation before issuance is SPIRE’s behaviour; the SPIFFE specifications don’t require it. ↩ draft-ietf-oauth-spiffe-client-auth, OAuth working group, revision 03, sections 3.1, 3.2.2, 5.1, 8.1 and 8.2; the example metadata document is from section 3.2.2. ↩ Model Context Protocol: Authorization, specification version 2026-07-28: implementations using the stdio transport “SHOULD NOT follow this specification, and instead retrieve credentials from the environment”. ↩ AWS: IAM roles for service accounts; Google Cloud: workload identity federation, which also accepts AWS and Azure identities; Microsoft: managed identities for Azure resources. ↩ IETF Web Bot Auth working group, formed 23 October 2025; draft-ietf-webbotauth-httpsig-protocol, revision 01, which signs requests with HTTP Message Signatures (RFC 9421). ↩ draft-ietf-oauth-identity-assertion-authz-grant, OAuth working group, revision 06, sections 4.3 and 4.4. ↩ Okta, Okta brings first-class identity to AI agents with Agent SSO, 24 August 2026. ↩ RFC 8693: OAuth 2.0 Token Exchange, January 2020, sections 4.1 (act, including that prior actors are informational only) and 4.4 (may_act). ↩ Model Context Protocol: Authorization, Security Considerations, “Access Token Privilege Restriction”, specification version 2026-07-28. ↩ draft-ietf-oauth-identity-chaining: OAuth Identity and Authorization Chaining Across Domains, OAuth working group, revision 17. ↩ RFC 8705: OAuth 2.0 Mutual-TLS Client Authentication and Certificate-Bound Access Tokens, February 2020; RFC 9449: OAuth 2.0 Demonstrating Proof of Possession (DPoP), September 2023. ↩ RFC 9396: OAuth 2.0 Rich Authorization Requests, May 2023. ↩ Agent Payments Protocol, version 0.2, checkout and payment mandates as verifiable digital credentials; AP2 repository. ↩ Ruoming Pang et al., Zanzibar: Google’s Consistent, Global Authorization System, USENIX ATC 2019. ↩ ↩2 Open Policy Agent (Rego); Cedar policy language. ↩ Enforce least-privilege authorization in multi-agent AI chains using Cedar, AWS Security Blog. ↩ Joseph W. Cutler et al., Cedar: A New Language for Expressive, Fast, Safe, and Analyzable Authorization, OOPSLA 2024. ↩ ↩2 Arnar Birgisson, Joe Gibbs Politz, Úlfar Erlingsson, Ankur Taly, Michael Vrable and Mark Lentczner, Macaroons: Cookies with Contextual Caveats for Decentralized Authorization in the Cloud, NDSS 2014. ↩ Agent2Agent (A2A) Protocol Specification, version 1.0.0 (retrieved November 2026), sections 4.5, 7.5, 7.6 and 8.4. ↩ draft-ietf-oauth-transaction-tokens, OAuth working group, revision 11, sections 6, 9.2.1–9.2.3, 12.1, 13.1, 13.13 and 13.15. ↩ Scott Rose, Oliver Borchert, Stu Mitchell and Sean Connelly, Zero Trust Architecture, NIST SP 800-207, August 2020: the definition (section 2), the policy decision and enforcement points (section 2, figure 1), protecting the policy management tool (section 5.5), non-person entities (section 5.7) and cataloguing shadow IT (section 7.3.2). ↩ ↩2 ↩3 ↩4 Model Context Protocol: Tools, specification version 2026-07-28: tools/call carries a name and arguments, each tool declares an inputSchema, and servers must implement proper access controls. ↩ ↩2 SpiceDB; OpenFGA, a CNCF project; Envoy external authorization filter. ↩ SpiceDB, Consistency: checks default to minimize_latency, which can leave a window for the New Enemy Problem; a ZedToken is stored alongside the updated content in the application database. ↩ AWS, Amazon Bedrock AgentCore: policy scope and example policies, which condition on tool input such as context.input.amount. ↩ OPA: SQL data filtering with partial evaluation; Oso: local authorization; SpiceDB, Protecting a list endpoint, which recommends LookupResources below about 10,000 accessible resources and bulk checks or materialization above that. ↩ ↩2 Cedar, Authorization: an applicable forbid overrides any permit, and a policy whose evaluation errors is skipped. ↩ LiteLLM; Palo Alto Networks, Announcing general availability of Prisma AIRS AI Gateway, July 2026; Cloudflare AI Gateway; Kong AI MCP Proxy plugin; agentgateway; Envoy AI Gateway; Azure API Management AI gateway. ↩ Varonis Threat Labs, SearchLeak, remediated by Microsoft as CVE-2026-42824. ↩ Ponemon Institute and DTEX, 2026 Cost of Insider Risks Global Report. ↩ OpenID Continuous Access Evaluation Profile 1.0, final; OpenID Shared Signals working group, final specifications approved September 2025. ↩ OpenAI, Introducing Shirudo, 23 November 2026; Shirudo documentation, pre-release (0.0.0-dev), read November 2026. ↩ CrowdStrike, Channel File 291 Incident: External Technical Root Cause Analysis, 6 August 2024; Microsoft, Helping our customers through the CrowdStrike outage, 20 July 2024. ↩ --- # Agentic AI on Kafka and Flink: What Agents Really Change in Streaming URL: https://platformatory.io/blog/agentic-ai-streaming-use-cases/ Published: 2026-11-22 Authors: Pavan Keshavamurthy Categories: AI, Kafka, Stream Processing, Apache Flink I’d been heads-down for a while, and Current ‘26 was a useful window onto what the rest of the streaming world had been building. For a few months I’d been curious what Redpanda was shipping, and what exactly an agentic data plane is. I also attended a Confluent hackathon, which turned out to be mostly a guided copy-and-paste exercise, and came away knowing what Lightning Tables are. What everyone seems to be up to is agents: the major streaming vendors all shipped agent infrastructure in 2026. Confluent added a fifth pillar to its platform, called Query, and put agents on top of it.1 Redpanda built an agentic data plane,2 and Apache Flink grew an agents sub-project.3 Read against their own documentation, most of it is a pattern Kafka users have run for years under another name. A few things are new, and they’re mostly missing from the launch slides. The question for anyone running Kafka and Flink is which of these launches to buy, which to build, and which to ignore. Sorting them takes two piles: familiar patterns under a new name, and use-cases that genuinely didn’t exist before agents. The pivot has a cause. The log itself stopped being something a vendor could charge a premium for. Diskless topics. Apache Kafka accepted KIP-1150 on 2 March 2026, putting object-storage topics on the upstream road map.4 Forks and rewrites. StreamNative shipped Ursa for Kafka in April 2026, a fork of Kafka 4.2 and later on lakehouse-native storage.5 Aiven, AutoMQ, WarpStream and Bufstream sell their own takes on the same idea. Queues in the box. Share groups, Kafka’s native queue, have been production-ready since 4.2.6 Consolidation. Confluent now describes itself as “an IBM company”.1 When the protocol is common property and storage is moving to object storage, the margin moves up the stack, to serving, processing and governance. My read is that agents are the story that sells those layers. Each product still has to be judged on what it does that the layer beneath it couldn’t. Mostly familiar patterns 4 November 2026: Lightning Tables and the Real-Time Context Engine. Confluent’s Streamhouse adds Query as a fifth pillar beside Stream, Connect, Process and Govern. At its centre is Lightning Tables: switch it on for a topic and the topic becomes a read-only table, refreshed within about 100 ms, queryable from SQL, HTTP, the CLI, JDBC and MCP. Confluent’s own tests put queries at 10 to 100 ms and above 1,000 per second, on AWS only for now.17 The Real-Time Context Engine is the MCP face of the same tables: an agent lists the topics, reads their schemas and writes its own SQL.8 The SQL is single-table. Key lookups, filters, ORDER BY and LIMIT work; joins, aggregates, GROUP BY and subqueries are rejected.9 Anything worth asking still gets computed upstream in Flink and written to a topic first. ksqlDB’s pull queries already fetched “the current state of a materialized view”,10 and Kafka Streams has served its state stores to applications for years. The docs are admirably plain about the limits. A managed, MCP-addressable materialized view is a convenience, and an agent reading a schema and writing SQL against it is what a catalog and a SQL client have always offered. The “context” here is business state (orders, stock, accounts); conversation memory for agents is a different problem, and the product doesn’t claim to solve it. 19 May 2026: Streaming Agents, generally available. Confluent’s event-driven agents run inside Flink and Kafka pipelines.11 Flink Agents, an Apache Flink sub-project, does the same in the open and keeps agent memory in Flink state.3 Stripped of the name, this is model inference inside a stream operator, keyed state used as memory, and an event-driven service around it. Each piece is old; a language model as the operator raises a problem of its own, which comes back in the second pile. The rest of the year. The pattern holds: Forecasts and anomalies that trigger an agent to restock or escalate:12 complex event processing with an alert that runs a runbook. Share groups for agent tasks: a work queue, and a weak one for the jobs agents hand each other (below).6 AI gateways and agent data planes: an API gateway and an identity provider. Redpanda’s version issues short-lived, agent-bound tokens and logs every agent interaction for replay, which points at a real problem picked up below.2 Agent action logs: event sourcing. Managed MCP servers and agent skills for coding assistants: developer tooling, welcome and unrelated to streaming. Diskless storage and the “streamhouse”: storage cost architecture, marketed alongside the agent features. The launch What it was already called Lightning Tables, context engines Materialized-view serving (ksqlDB pull queries, Kafka Streams state stores) Streaming Agents, Flink Agents Inference in a stream operator, keyed state, an event-driven service Forecast or anomaly triggers an agent Complex event processing and a runbook Share groups for agent tasks A work queue AI gateway, agentic data plane An API gateway and an identity provider Agent action log Event sourcing Diskless, streamhouse Storage cost architecture Updated 24 November 2026: share groups and agent-to-agent traffic. Kafka as the transport between agents has been pitched since Confluent’s April 2025 case that Agent2Agent needs it: one event backbone, where agents publish what they know and subscribe to what they need.13 For the jobs agents hand each other, the fit is poor, share groups included. Exclusive jobs. Share groups do track each record. A consumer acquires it under a lock, 30 seconds by default, then accepts, releases or rejects it, and the broker counts deliveries.14 An agent task that outlives the lock goes back to the pool and is handed out again unless the consumer keeps renewing it,15 and after five attempts the record is archived, out of the queue, with no dead-letter queue until KIP-1191, accepted but not yet released, ships.16 Head-of-line blocking. Each partition has a capped window of records in flight. Once it fills, fetches return nothing until acquired records are settled, so a few slow jobs hold up the fast ones behind them.14 Selective fan-out. Neither consumer groups nor share groups filter. Every member sees the whole topic, so routing work to the agents that can handle it takes a topic per audience or filtering in the client. Foreign parties. A Kafka client talks to each partition’s leader directly, so every broker has to be reachable by every client. Exposing that beyond a private network takes a Kafka-aware proxy that routes by SNI, a private endpoint per broker, or an HTTP front end, and each puts a gateway at the edge that speaks some other protocol anyway. Share groups suit what the Kafka project itself recommends them for, records processed one at a time:17 short, idempotent work fanned out from a topic you already have. Agent-to-agent calls across a boundary belong on A2A over HTTP, with a job queue or a durable workflow engine behind them. Kafka earns its place behind that boundary, as the log every agent’s actions and outputs are recorded to. Five things agents genuinely change in streaming The new pile is shorter, and most of it is about the consumer. Replay no longer reproduces. Streaming’s deepest promise is that a log replayed through deterministic operators gives the same result. Exactly-once covers Flink’s state and Kafka’s offsets, and a model call sits outside both. Replay a pipeline whose operator is an agent and it makes the calls again, gets different answers, and bills you a second time. The fix is to treat model output as data: write every request, response and model version to the log, and have replay read the recorded output instead of asking again. Once that exists, a second capability follows. Fork the log at a point in history and run a new agent version against everything that happened since, which is a backtest for agents. AgileLog, at SOSP this year, proposes a shared log with forking primitives for exactly this.18 The consumer acts for someone. A service account does a fixed job, and its permissions are decided when the service is designed. An agent acts on a user’s delegated authority and chooses its actions at runtime, so the authorization decision moves to the moment of each action, and the audit has to record why it acted (the prompt, the context it retrieved, the tool it chose) as well as what it did. Redpanda’s agent-bound tokens and replayable interaction logs are the most direct answer shipped so far.2 Every message costs money. Backpressure used to be about throughput. When the consumer is a model, it is also about the bill. With \(r\) events a second, a fraction \(f\) of them sent to a model, \(t\) tokens a call and a blended price of \(p\) per token, the daily cost is \[C_{\text{day}} = r \cdot f \cdot t \cdot p \cdot 86{,}400\] For a modest security or commerce topic at 50,000 events a second, sending 1% to a model at 2,000 tokens a call and an assumed $3 per million tokens (illustrative figures throughout): \[C_{\text{day}} = 50{,}000 \times 0.01 \times 2{,}000 \times \frac{\$3}{10^6} \times 86{,}400 \approx \$259{,}000\] A topic that spikes tenfold multiplies the bill tenfold. Which events earn a model call (sampling, tiering, caching) becomes an operator’s decision with a price on it, alongside partition counts and retention. Threat response at machine speed. Kafka in front of the SIEM is an old idea: security data pipelines that route, cut and enrich logs before indexing built a business out of it, with Cribl alone reported past $200 million in annual recurring revenue.19 The adversary is what changed. In the espionage campaign Anthropic disrupted in late 2025, AI performed 80 to 90% of the work, at peak making thousands of requests, often several a second.20 Response measured in hours stops being good enough against that, and detection is moving into the pipeline: SOC Prime’s DetectFlow runs Sigma rules with Flink on live Kafka streams, before the data reaches the SIEM.21 The layers are network flows, DNS, identity and endpoint signals, far more than observability telemetry, and the cost equation above rules out sending all of it to a model. The shape that works is tiered: cheap rules and models on every record, and an agent triaging the small residue that’s left. That makes Kafka and Flink necessary infrastructure where detection fans out to several detectors, correlates signals across layers, or needs to replay history against a new rule. The usual objection is that a broker is one more hop before detection. That stops holding when the broker runs next to the workload, which is a story for another day. Updated 24 November 2026: runtime shielding. Response is moving onto the host too. Shirudo, an open-source Linux runtime from Cisco and OpenAI released on 23 November 2026 and still pre-release, lets an agent write a small eBPF program, or a bytecode check inside a running JVM, that blocks a vulnerable code path until the real patch lands. Its launch demonstration blocked a Java4Shell exploit against a running Elasticsearch without a restart.22 Delivery stays with the operator: shields are signed with the operator’s own key, served from its own registry and pulled by every host about once a minute by default, and a shield copied in by hand loads offline.23 It’s fantastic technology, and still speculative. The dependence it adds is on the frontier model that writes the shield, since the runtime “does not judge what a upatch does”:23 an operator approving one vouches for kernel code a model wrote against a disclosure that may be hours old. The failure it invites is on record. On 19 July 2024, a CrowdStrike content update, configuration data delivered from the cloud and interpreted by its kernel driver, hit an estimated 8.5 million Windows machines, and the fixes that followed were staged rollout rings and customer control over each update.24 BGP and DNS taught the same lesson at internet scale: the systems every host trusts automatically have caused some of the largest outages.25 Expect shields to join them unless they move through rings like any other change. Keeping attackers out still comes first. Where a workload can tolerate it, ring-fence it with an air-gap, and treat shields as a stopgap inside the fence for the code paths an insider or a poisoned update can still reach. Shirudo runs offline, so the two compose. Continual learning from agent traces. Online learning on Kafka and Flink is established practice. ByteDance’s Monolith logged user actions to Kafka, joined features in Flink and updated model parameters as the data arrived, back in 2022.26 Continual learning for agents mostly changes prompts, retrieval, memory, tools and routing, and only sometimes weights, in a governed loop from production traces.27 Kafka’s part in that loop is specific: Trace capture. Every request, tool call, response and model version, which is the same record that makes replay reproducible. Late-label joins. Feedback, grader scores and outcomes arrive minutes or days later; Flink joins them to the trace by ID. Drift detection. Shifts in inputs, tool-call mix and failure clusters, while they’re happening. Fast updates. Memory, retrieval and prompt changes that ship without retraining. The training and regression sets belong in Iceberg, large trajectories belong in object storage with a pointer in the message, and for agents, weight retraining runs in batch, where Kafka’s milliseconds buy nothing. The loop needs numbers to steer by: Freshness: event-to-trainable lag, and time from a fix to its promotion. Labels: label delay, coverage, and grader agreement with humans. Quality: regression-set pass rate, held-out regressions, calibration. Drift: input distribution, tool-call distribution, new failure clusters. Safety: rollback rate, and canary deltas against the current version. Cost: tokens per resolved task. The recorded model outputs that make replay honest are the same records this loop learns from. What each is worth Ranking both piles by what they’re worth and what they cost changes the reading order. The scores are my own assessment, from 1 to 5, for a team already running Kafka and Flink. Value is the upside if it works: revenue, risk avoided, quality, money saved. Cost is what it takes to adopt and run: new spend, operations, people and tokens. My assessment, scored 1 to 5, November 2026. Opportunity Pile Value Cost Why Threat response at machine speed New 5 4.5 Breach and regulatory cost avoided; flow-level volume and round-the-clock operations Continual learning New 4.5 3.6 Agent quality compounds; labelling, graders and evals cost people Delegated principal New 4.2 3.4 Often the gate to production; identity plumbing across teams Record and replay of model outputs New 4.2 2 Reproducible, testable agents; mostly design discipline and storage Agent action log Old 4 1.3 Audit, evals and replay start here, on a topic you already have Diskless storage Old 3.7 2.8 A real saving on cross-zone traffic; a migration, and no upstream release yet Budget backpressure New 3.6 1.8 Its value is the bill it cuts; mostly a policy layer Share groups for agent tasks Old 2 1 Free from Kafka 4.2; lock timeouts, no dead-letter queue and no filters make a poor job queue for agents AI gateway, agent data plane Old 3 2.5 Governance is needed anyway; buying beats building Forecast or anomaly triggers an agent Old 2.8 2 Cheap complex event processing; the agent adds little over a runbook Context engines Old 2 3 New managed spend, Flink still upstream, single-table queries Streaming and Flink Agents Old 2 4 Model calls in the hot path, replay cost, operational coupling MCP tooling for coding assistants Old 1.5 1 Pleasant and free with the platform The cheapest wins are in the new pile, or rest on infrastructure you already own. Recording model outputs in the action log and putting a budget on model calls pay off three times, in audit, in evals and on the bill, and continual learning is built on the same records. At the illustrative $259,000 a day above, sampling out a tenth of the model calls saves about $26,000 a day. The three strategic bets (threat response, continual learning and the delegated principal) carry the most value and the most cost, and none of them is a single product you can buy: each is an integration project. The headline launches, agents inside the pipeline and context engines, score lowest for what they cost, unless the data is born as events and decisions turn over in seconds. Diskless storage is the familiar pattern worth chasing, for savings that have little to do with agents. Which agentic streaming launch to buy, and when As of November 2026, the choice follows where the data is born and what the agent does with it: The data is born as events and the decision changes within seconds (fraud, stock, dispatch, security): stream-native serving earns its keep. Check whether single-table queries are enough before buying a serving layer that can’t join. The agent needs joins and aggregates over live data: a streaming database (Materialize, RisingWave, Feldera) or Flink writing into a database you already run. The context lives in systems of record (the CRM record, the contract, the ticket): MCP on the source or a read replica, or change data capture into a store you operate. A stream adds a copy without adding freshness the agent can use. The agent needs crash-safety, long waits and retries: a durable execution engine (Temporal, Restate, DBOS) handles model calls as side effects more naturally than an agent inside a stream operator. Agent tasks need dispatching: a job queue or a durable execution engine; share groups only for short, idempotent work on Kafka 4.2 or later. Agents need an action log: a topic you already have, with model outputs recorded so the log replays. Security: Kafka and Flink where detection fans out, correlates or replays; filtering at the sensor everywhere else. Continual learning: Kafka carries traces and joins labels, and Iceberg keeps what the models learn from. These piles would shift if the products changed. A serving layer that joins and searches, a log that records and replays model outputs as a primitive, or budget-aware backpressure in the broker would each move something from the second pile into a product worth buying. None has shipped yet. Until one does, most of what’s being sold as agent infrastructure is infrastructure you already run. Confluent introduces its Streamhouse architecture, IBM Newsroom, 4 November 2026. Performance figures are Confluent’s internal testing. ↩ ↩2 ↩3 Redpanda acquires Oxla, launches Agentic Data Plane, Redpanda, 28 October 2025. ↩ ↩2 ↩3 Ververica debuts Flink Agents, SiliconANGLE, 15 October 2025. ↩ ↩2 Diskless Kafka: what happens when brokers stop owning the data?, SoftwareMill; Data streaming trends Q3 2026, Kai Waehner, 21 September 2026. ↩ StreamNative introduces Lakestream architecture and launches native Kafka service, Business Wire, 7 April 2026. ↩ Kafka share groups, Thoughtworks Technology Radar, 4 November 2026; Apache Kafka 4.2 upgrade notes: “production-ready in Apache Kafka 4.2”. ↩ ↩2 Lightning Tables in Confluent Cloud, Confluent documentation, updated 16 November 2026. ↩ Query a Lightning Table with MCP, Confluent documentation. ↩ Lightning Tables SQL reference, Confluent documentation, updated 16 November 2026. ↩ Queries, ksqlDB documentation. ↩ Confluent Cloud Q2 2026 launch, Confluent, 19 May 2026. ↩ New in Confluent Intelligence and AI tools, Confluent, Q3 2026. ↩ Sean Falconer, Why Google’s Agent2Agent protocol needs Apache Kafka, Confluent, 28 April 2025. ↩ KIP-932: Queues for Kafka: acquisition locks, delivery counts, a delivery attempt limit of 5 by default and a cap on in-flight records per share-partition; the lock default is share.record.lock.duration.ms, 30,000 ms, in the Kafka 4.2 group configs. ↩ ↩2 KIP-1222: Acquisition lock timeout renewal in share consumer explicit mode. ↩ KIP-1191: Dead-letter queues for share groups, accepted. ↩ Apache Kafka 4.2 upgrade notes: “Use share groups in cases where records are processed one at a time, rather than as part of an ordered stream.” ↩ Bhat, Hong, Noguera, Ganesan and Alagappan, AgileLog: a forkable shared log for agents on data streams, SOSP 2026. ↩ Market guide 2025: the rise of security data pipelines, Software Analyst. ↩ Disrupting the first reported AI-orchestrated cyber espionage campaign, Anthropic, 13 November 2025. ↩ SOC Prime’s DetectFlow Enterprise moves threat detection to the data ingestion layer, Help Net Security, 12 March 2026. ↩ OpenAI, Introducing Shirudo, 23 November 2026; Cisco, Expanding the defender’s window with self-defending infrastructure, 23 November 2026. ↩ Shirudo documentation and repository, pre-release (0.0.0-dev), read November 2026; it requires a patched bpf-next kernel and a TPM 2.0. ↩ ↩2 CrowdStrike, Channel File 291 Incident: External Technical Root Cause Analysis, 6 August 2024; Microsoft, Helping our customers through the CrowdStrike outage, 20 July 2024. ↩ Meta, More details about the October 4 outage, 5 October 2021 (a backbone command, then DNS servers withdrawing their BGP advertisements); AWS, Summary of the Amazon DynamoDB service disruption in US-EAST-1, October 2025 (an empty DNS record from DynamoDB’s DNS automation). ↩ Monolith: real time recommendation system with collisionless embedding table, ByteDance, 2022. ↩ Continual learning for AI agents and LLM systems, Arize, reviewed 16 August 2026. ↩ --- # Running Agentic AI as an Enterprise Platform URL: https://platformatory.io/blog/platform-engineering-3/ Published: 2026-11-21 Authors: Pavan Keshavamurthy Categories: Platform Engineering, AI, Software Engineering In 2021 we published a platform engineering manifesto with a deliberately cheeky teaser: Platform Engineering is dead. Long live platform engineering! The case was short. A platform team is justified once an engineering organisation outgrows the Dunbar number. Its job is to extract cross-cutting concerns once, instead of in every team. Its success shows up in three numbers: developer satisfaction, platform usage, and time to first production deployment. Its failure mode is a “mess of 99 problems cherrypicked straight from the CNCF landscape graveyard of tools”. Five years on, the list of 99 problems has been rewritten, and most of the new entries are agents: in support queues, claims desks and ops runbooks, and most visibly in engineering. A CTO who has bought coding-agent seats for every team now has a few hundred autonomous actors opening pull requests, a few dozen MCP servers that nobody registered, three AI gateways, two harnesses per team, and a token bill with no owner. The Dunbar argument also breaks: agents have no Dunbar number, and nothing stops one engineer from starting fifty of them before lunch. Which leaves that CTO with one question: what does it take to run agentic AI as a platform for the whole enterprise? The software factory is the place to answer it first. Agents already work there at volume, and a bad change shows up in a queue you can measure. Platform engineering has shifted twice already: from infrastructure tribes run as a shared service, to the platform as a product, with self-service golden paths for developers.1 Running agents is the third shift (Platform Engineering 3.0, if you count from the shared-services teams; counted from internal developer platforms it’s the second, and “3.0” elsewhere means AI inside the platform2). The consumers are now developers and agents, agents are also workloads the platform hosts, and the resources it governs are models, tokens, tools, context and non-human identities. A developer reads the docs, files a ticket when the golden path is wrong, and has a manager. An agent does none of those things, will run the same wrong path ten thousand times overnight, and acts with whatever authority it was handed. What most enterprises have today is craft production with better tools. Every team picks its own machine and sets it up its own way, so quality depends on the craftsman. The numbers come mostly from surveys run by vendors who sell the cure, so treat them as directional: Agents per organisation: a mean of about 37 in December 2025, with the estate roughly doubling in four months.3 Unmonitored agents: 47% of the roughly 3 million agents deployed by surveyed firms were not actively monitored or secured. 88% of organisations reported a confirmed or suspected agent-related security or privacy incident in the prior year.3 Accountability: only 28% of organisations can trace an agent’s action back to a human sponsor.4 Tooling sprawl: public registries list over 20,000 MCP servers.5 One curated list tracks more than 220 AI gateways.6 Outcome (forecast): over 40% of agentic AI projects cancelled by the end of 2027, on cost, unclear value or inadequate risk controls.7 AI is an amplifier: it magnifies an organisation’s existing strengths and weaknesses, and a high-quality internal platform correlates directly with the ability to get value from it.8 Without one, AI creates local pockets of productivity that get lost in downstream chaos. The evidence is a survey of nearly 5,000 technology professionals and a correlation, so it can’t prove the platform causes the gains. It does match what anyone who has watched a hundred agent-generated PRs queue behind four reviewers already suspects. AI makes code cheaper to write without making it much faster to ship, because the work moves to specs, evals and review. If that’s right, the open question is what has to be built so the moved work doesn’t pile up. Factories came from what was built around the machines. By 1905, Sakichi Toyoda’s power loom carried a device that stopped the machine the moment a weft thread broke or ran out.9 Before that, a broken thread meant a loom quietly weaving yards of defective cloth until someone noticed. Once the loom could stop itself, one operator could tend many machines. The idea became jidoka, one of the two pillars of the Toyota Production System: build the check into the machine and stop the line at the first defect.10 Every industrialisation since has the same ingredients, and each one maps onto the software factory: Interchangeable parts and standard interfaces: MCP for tools, A2A between agents, OpenTelemetry for signals, one identity scheme. Standard work: the documented best way to do a task, which in the factory means context files, skills and golden paths that an agent loads instead of rediscovering. Stopping the line on defects: validation gates that fail a change before a human ever sees it. A measured yield: good output per unit of input, tracked continuously. Stripe is the clearest existence proof that this works for code. Its “minions” are one-shot, unattended coding agents, and over 1,300 pull requests merged each week at Stripe are written entirely by them, up from about a thousand ten days earlier.1112 Every PR is reviewed by a human. Around the agent, Stripe built a line: Devboxes: pre-warmed, ready in about 10 seconds with Stripe’s code and services loaded, and isolated from production and the internet.11 Toolshed: one internal MCP server shared by all of Stripe’s agents, with around 400–500 tools. Each agent gets a curated subset, and minions get a deliberately small default set.1213 Blueprints: workflows defined in code that direct a run, mixing agent steps (implement the task, fix CI failures) with deterministic ones (run the linters, push) that never call a model. CI gets at most two rounds before the branch goes back to its human operator.12 StrongDM pushes the idea to its limit with a “dark factory”, a term borrowed from manufacturing for a factory that runs with the lights off. Its rule is that humans don’t review code. Humans write specifications and curate scenarios, and agents are validated against digital twins of systems like Okta and Slack.1415 Its yardstick for a working factory is at least $1,000 of tokens per engineer per day.15 Its agents once produced a placeholder that passed the tests and did nothing.16 That’s the defect jidoka exists to catch: in a lights-out factory the validation suite is the definition of correct, and an incomplete suite ships incomplete software. The yield equation Where the cost of a factory actually goes is simple enough to write down. Let an agent run cost \(c_{run}\) (tokens plus sandbox time). Let \(p\) be the fraction of runs that produce a pull request, \(m\) the fraction of those that merge, and \(c_{rev}\) the human cost of reviewing one pull request. Every run is paid for, every PR is reviewed, and only merged PRs count, so the cost per merged change is: \[C_{merged} = \frac{c_{run}}{p \cdot m} + \frac{c_{rev}}{m}\] An illustrative case, with assumed inputs: \(c_{run} = \$5\), \(p = 0.6\), \(m = 0.7\), and 20 minutes of review at a loaded $90 an hour, so \(c_{rev} = \$30\). \[C_{merged} = \frac{5}{0.42} + \frac{30}{0.7} \approx \$11.90 + \$42.86 \approx \$54.76\] About four-fifths of that cost is review, and it is divided by the merge rate. Two levers follow: Gates before review raise \(m\) and cut \(c_{rev}\). A change that fails tests, policy or scenario checks goes back to the agent without consuming a reviewer. If gates lift \(m\) to 0.85 and cut review to 12 minutes (\(c_{rev} = \$18\)), the cost per merged change falls to about $31, with no change of model. A better model mostly moves \(c_{run}\), the smallest term, unless it also raises \(p\) and \(m\). Halving \(c_{run}\) in the base case saves about $6. Review capacity also caps throughput, whatever the agents produce. With \(R\) reviewer-hours a week and \(t\) hours per review, merged changes per week are bounded by: \[\text{merged/week} \le \frac{R}{t} \cdot m\] At 20 minutes a review and \(m = 0.7\), every 100 reviewer-hours a week yields at most 210 merged changes. Starting more agents fills the queue without raising that ceiling. Gates and standard work are the only things that raise it, because they shorten \(t\) and lift \(m\). The condition that flips this: at dark-factory token rates, \(c_{run}\) stops being small. At $1,000 a day per engineer, an engineer overseeing 20 merged changes a day spends $50 per change on tokens alone, as much as the review term. Past that point, routing and token budgets matter as much as gates. That is where the traffic plane earns its place. The line, layer by layer Substrate: Kubernetes, with operators for everything Agents need a place to run that is isolated, stateful, cheap when idle, and quick to wake. Kubernetes now has a standard shape for this. The SIG Apps agent-sandbox subproject defines a Sandbox custom resource for singleton, stateful workloads such as agent runtimes: one pod with a stable hostname and network identity, isolated by gVisor or Kata Containers, kept warm by a SandboxWarmPool, and able to scale to zero and resume where it left off.17 Agents themselves are becoming resources too. kagent, a CNCF Sandbox project, declares agents, tools and model configurations as CRDs, and Kagenti gives agents SPIFFE identities.1819 My bet is that the substrate stays Kubernetes-centric even when the work runs elsewhere. Operators will reconcile a sandbox on a hyperscaler, a model endpoint on a GPU cluster, and an MCP server in a SaaS tenant, the way Crossplane taught platform teams to reconcile cloud resources they don’t host. The price is real: more CRDs, more reconciliation loops, and upgrades that need choreography. It’s the price the last platform era already paid, and it buys one control plane where policy lives. Identity: the deepest rabbit hole The first layer of the identity problem has already been tidied up. The MCP specification of 2025-11-25 made Client ID Metadata Documents the preferred way for a client to identify itself: the client ID is a URL that hosts the client’s own metadata, and Dynamic Client Registration dropped to a fallback. The 2026-07-28 revision deprecates DCR for new implementations.20 CIMD answers which client software is this? A factory needs more. It needs to know which agent instance is acting, on whose behalf, and with what delegated authority, and it needs to revoke that authority without revoking the human’s. That is where the standards are still drafts: Enterprise Managed Authorization, a stable MCP authorization extension, lets the enterprise identity provider decide which clients reach which MCP servers. The client obtains an Identity Assertion JWT Authorization Grant (ID-JAG, the mechanism behind Cross App Access) from the IdP and exchanges it at the MCP server’s authorization server. The ID-JAG itself is still an IETF draft, and implementations track different revisions.21 The IETF WIMSE working group’s AIMS draft gives each agent exactly one workload identifier, optionally a SPIFFE ID, and builds authorisation on OAuth.22 A companion draft profiles it for platforms that host many agent instances per customer.23 Credential swapping at the gateway keeps enterprise credentials out of the sandbox entirely: the gateway inserts the backend credential as the request leaves.24 Vendors are shipping ahead of the standards. Okta’s Agent SSO, which implements Cross App Access, became generally available in August 2026, and Microsoft’s Entra Agent ID in April. Each builds on a different subset of the drafts.2526 Anyone buying identity for agents in 2026 should assume one migration, and choose the vendor whose exit path is clearest. The traffic plane: one plane, three routing jobs Everyone in the enterprise will have access to frontier models and to self-hosted ones (when to run your own is a question of self-hosting economics and sovereignty). So routing becomes a platform concern, and the gateway market has exploded accordingly. “Routing” covers three separate jobs, and most of the confusion comes from treating them as one: Model selection, which model should answer this request: vLLM Semantic Router classifies each request and picks a model. It can also filter jailbreaks and PII and cache semantically, all in the request path.27 Inference endpoint picking, which replica of that model, given KV-cache contents and load: the Gateway API Inference Extension, with llm-d as a primary implementation.28 Agent and tool traffic, governing MCP and A2A calls: agentgateway, a Linux Foundation project, handles LLM, MCP and A2A traffic in one data plane.29 Budgets, quotas and credential swaps belong in the same plane. Azure’s AI gateway, for one, enforces tokens-per-minute limits and returns a 429 when a project exceeds them.30 My rule: one traffic plane per routing job, run by the platform team, preferably on one proxy family. Two hundred and twenty gateways is two hundred and nineteen places where policy drifts. Durable execution A factory run waits on CI, on a flaky dependency, and for days on a human approval. Agent processes that keep their state in memory lose it all on a crash and pay for the tokens twice. Durable execution is now a standard pairing: Temporal’s integration with the OpenAI Agents SDK, generally available since March 2026, runs the agent loop as a workflow and model calls as activities.31 Restate, DBOS and Inngest fill the same niche with different trade-offs, licences among them: only Temporal and DBOS of the four ship under OSI-approved licences.32 For a tier the whole enterprise depends on, the licence is part of the architecture. Context and standard work Standard work in the factory is context. AGENTS.md (now stewarded by the Agentic AI Foundation, in over 60,000 repositories) and SKILL.md turn “how we do things here” into versioned, reviewable files that agents load.33 Stripe’s curated tool subsets are standard work too: an agent offered 500 tools wastes context choosing among them. Context also outlives tools. A choice of agent framework is reversible in roughly 12 to 18 months; context architecture is much harder to change.34 So spend the standardisation budget on context, and spend little of it on mandating an SDK. The factory’s context is mostly code, docs and tickets. Business agents need enterprise data, and that pulls context into the data platform. I expect it to be served from lakes that handle vectors natively, but that is a prediction: Iceberg has no native vector index today, so similarity search over it means a full scan or a separate system.35 The live bets are Lance as a table format, S3 Vectors as a storage class, and each warehouse vendor’s own engine. The memory hierarchy covers the tiers underneath. Audit and telemetry are two streams The last platform era taught teams to sample hard: keep the errors and the slow traces, drop the rest. Agents break that rule for one class of data. Every prompt, tool call, identity and approval is evidence. A security team investigating a prompt injection needs all of it, kept long enough to replay. Operational telemetry can still be sampled. So the factory should run two streams: Audit: complete, durable, ordered, replayable, and retained by policy. It’s a log in the database sense, and it should be built like one. Ops telemetry: OpenTelemetry end to end, tail-sampled at collectors near the source. The GenAI and agent conventions are still marked Development and moved to their own repository in June 2026, so expect attribute churn.36 Next, I expect classification to move toward the edge. Small models in collectors and gateways would flag injections, data leaks and runaway loops before anything ships centrally, the way vLLM Semantic Router already classifies requests in-path. Treat that as speculation. I’d call it wrong if, two years from now, guardrail inference still lives only in central SaaS consoles. Gates: the andon cord Every validation gate is an andon cord. Tests, type checks, policy-as-code, scenario suites against digital twins, and a budget check each stop the line and send the change back to the agent with the failure attached. Human review comes after the gates. The yield equation puts the gates first among the layers: they’re the only one that improves both terms. Frameworks: standardise the contracts Enterprises can’t sustain 200 agent frameworks, and they can’t mandate one either. Teams will route around a decree, and the frameworks themselves are consolidating anyway: Microsoft merged AutoGen and Semantic Kernel into Microsoft Agent Framework 1.0 in April 2026.37 The workable rule sits one layer above the frameworks: fix the contracts (MCP, A2A, OTel, the identity scheme, the traffic plane, the sandbox API), sanction two or three harnesses that honour them, and let teams choose inside that set. Rent the machines, own the line The strongest objection is that all of this is being productised as fast as it can be listed. GitHub’s Agent HQ runs Claude and Codex agents inside the pull-request workflow.38 Claude Code, Codex cloud, Cursor and Devin each ship sandboxes, admin planes and audit. AWS Bedrock AgentCore, Google’s Gemini Enterprise Agent Platform and Microsoft’s Foundry bundle runtime, identity, gateway and memory.39 A CTO who staffs a team to build the line in 2026 risks rebuilding CI in 2015: commodity by the time it works, with the platform team as the new bottleneck. Much of that is right, and most of the machines should be rented: the agents, the sandboxes, and very likely the durable-execution engine and the identity provider. Four things can’t be bought, because they encode your own system: Standard work: your context, skills and curated tools. The gates: your definition of a correct change, which no vendor can write for your payment flows or your claims engine. Identity and data policy: which agent may act for whom, on what. The yield metrics: cost per merged change, merge rate, review minutes per change, and gate-stopped versus reviewer-stopped defects. Buying the whole stack from one vendor is the right call when the estate is on one cloud, the engineering organisation is a few hundred people, one agent vendor covers most of the work, and regulatory exposure is low. Outside those conditions, the multi-model, multi-cloud and sovereignty requirements put you back to building the line. We sell platform engineering and agentic AI consulting, so we have a stake in this argument. The arithmetic above holds whoever builds the line. The forecasts point one way: Platforms: by 2027, 70% of organisations with platform teams will include generative AI capabilities in their internal developer platforms.40 Teams: by 2029, 60% of organisations will adopt smaller software engineering teams, up from 15% in 2026, with those “tiny teams” leaning on robust platform engineering teams for standardised, automated workflows and self-service AI tools.41 IDEs: by 2027, over 65% of engineering teams using agentic coding will treat the IDE as optional, shifting control, governance and validation to automated platforms.42 None of these forecasts names a role. Read together, they describe one: a platform team that runs the enterprise’s agentic AI platform, with the factory as its first line, staffed by engineers who understand distributed systems, identity and evaluation in roughly equal parts. Its KPIs update the 2021 three: Developer satisfaction becomes satisfaction from developers and reviewers, the people who absorb the factory’s output. Platform usage becomes the share of agent runs on the paved road: sanctioned harness, registered identity, governed traffic plane. Time to first production deployment becomes time from ticket to verified merge, together with cost per merged change and the merge rate. When this is wrong The design loses under three conditions, each with a signal to watch: Agents learn to validate themselves well enough that external gates add little. Signal: merge rates of ungated agent PRs approaching gated ones across model generations. Vendor admin planes absorb the line, exposing policy, identity and gate hooks rich enough that no enterprise needs its own. Signal: whether the major agent platforms let you plug in your own gates and identity provider, or only their own. Dark factories prove review-free delivery safe for most changes. Then the yield equation loses its review term, and the line becomes almost entirely gates and token economics. That still makes it a platform job, though a different one. What to do this quarter Measure cost per merged change, merge rate and review minutes per change before buying more seats. Put every agent behind a registered identity with a human sponsor. The 28% who can trace agent actions today are the baseline to beat. Pick one traffic plane per routing job and move budgets and credential swaps into it. Write the gates before scaling the agents: tests, policy checks, and scenario suites for the systems where a wrong change is expensive. Split audit from telemetry, and size the audit store for replay. Sanction two or three harnesses on fixed contracts, and spend the standardisation effort on context. Not every company needs a platform team, only those past the Dunbar number. That threshold now counts actors: an organisation of forty engineers that runs four hundred agents has crossed it. Platform engineering is dead. Long live platform engineering. Platform Engineering community, “The story of platform engineering” (Team Topologies, 2019; “internal developer platform”, 2020; Gartner Hype Cycle, August 2022). https://platformengineering.org/blog/the-story-of-platform-engineering ↩ CNCF, “Evolving platform engineering for AI-native workloads,” 6 July 2026, https://www.cncf.io/blog/2026/07/06/evolving-platform-engineering-for-ai-native-workloads/; env0, “Platform Engineering 3.0: Practical Guidance for Scaling Infrastructure in the AI Era,” https://www.env0.com/resources-center/whitepaper-platform-engineering-3-0 ↩ Gravitee, “State of AI Agent Security Report 2026” (survey of 750 enterprise technology leaders; Gravitee sells API and agent gateways). https://www.gravitee.io/state-of-ai-agent-security ↩ ↩2 Cloud Security Alliance, “AI Agent Identity Sprawl: The Enterprise Authorization Crisis” (survey with Aembit, which sells workload and agent access products). https://labs.cloudsecurityalliance.org/research/csa-research-note-ai-agent-identity-sprawl-authorization-202/ ↩ Zuplo, “Shadow MCP: The Ungoverned AI Agent Tools Putting Your APIs at Risk” (estimate of public MCP servers, mid-2026). https://zuplo.com/learning-center/shadow-mcp-ungoverned-ai-agent-security ↩ awesome-ai-gateway, a curated list of 220+ AI gateways. https://github.com/cuihuan/awesome-ai-gateway ↩ Gartner, “Gartner Predicts Over 40% of Agentic AI Projects Will Be Canceled by End of 2027,” 25 June 2025. https://www.gartner.com/en/newsroom/press-releases/2025-06-25-gartner-predicts-over-40-percent-of-agentic-ai-projects-will-be-canceled-by-end-of-2027 ↩ DORA, “2025 State of AI-assisted Software Development.” https://dora.dev/dora-report-2025/; Google Cloud, “Announcing the 2025 DORA report.” https://cloud.google.com/blog/products/ai-machine-learning/announcing-the-2025-dora-report ↩ Toyota Motor Corporation, “The Birth of Jidoka” (Toyoda Power Loom, completed 1897; weft-halting device described in the 1905 model’s manual; origin of jidoka in the Toyota Production System). https://www.toyota-global.com/company/history_of_toyota/75years/text/taking_on_the_automotive_business/chapter1/section1/item4.html ↩ Lean Enterprise Institute, “Toyoda, Sakichi (1867–1930).” https://www.lean.org/lexicon-terms/toyoda-sakichi-1867-1930/ ↩ Stripe, “Minions: Stripe’s one-shot, end-to-end coding agents,” 9 February 2026. https://stripe.dev/blog/minions-stripes-one-shot-end-to-end-coding-agents ↩ ↩2 Stripe, “Minions: Stripe’s one-shot, end-to-end coding agents, Part 2,” 19 February 2026. https://stripe.dev/blog/minions-stripes-one-shot-end-to-end-coding-agents-part-2 ↩ ↩2 ↩3 ByteByteGo, “How Stripe’s Minions Ship 1,300 PRs a Week.” https://blog.bytebytego.com/p/how-stripes-minions-ship-1300-prs ↩ StrongDM, “The StrongDM Software Factory: Building Software with AI.” https://discover.strongdm.com/blog/the-strongdm-software-factory-building-software-with-ai ↩ Simon Willison, “StrongDM’s software factory,” 7 February 2026. https://simonwillison.net/2026/Feb/7/software-factory ↩ ↩2 Stanford CodeX, “Built by Agents, Tested by Agents, Trusted by Whom?,” 8 February 2026. https://law.stanford.edu/2026/02/08/built-by-agents-tested-by-agents-trusted-by-whom/ ↩ Kubernetes, “Running Agents on Kubernetes with Agent Sandbox,” 20 March 2026. https://kubernetes.io/blog/2026/03/20/running-agents-on-kubernetes-with-agent-sandbox; https://github.com/kubernetes-sigs/agent-sandbox ↩ CNCF, kagent project page (Sandbox, accepted 22 May 2025). https://www.cncf.io/projects/kagent/ ↩ Signadot, “Running AI Agents on Kubernetes: Agent Sandbox, kagent and More.” https://www.signadot.com/blog/running-ai-agents-on-kubernetes/ ↩ Model Context Protocol, “Client registration,” specification 2026-07-28. https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization/client-registration; SEP-991. https://modelcontextprotocol.io/community/seps/991-enable-url-based-client-registration-using-oauth-c ↩ Model Context Protocol, “Enterprise Managed Authorization” extension (io.modelcontextprotocol/enterprise-managed-authorization, stable). https://modelcontextprotocol.io/extensions/auth/enterprise-managed-authorization ↩ IETF WIMSE WG, “AI Agent Identity Management System (AIMS),” draft-ietf-wimse-aims. https://datatracker.ietf.org/doc/html/draft-ietf-wimse-aims ↩ IETF, draft-carleton-workload-authz-grant-00. https://www.ietf.org/archive/id/draft-carleton-workload-authz-grant-00.html ↩ Google Cloud, “Agent Compute Engine deep dive.” https://cloud.google.com/blog/topics/ai-infrastructure/agent-compute-engine-deep-dive ↩ Okta, “Okta brings first-class identity to AI agents with Agent SSO.” https://okta.com/newsroom/press-releases/okta-brings-first-class-identity-to-ai-agents-with-agent-sso/ ↩ Forkast, “Six vendors are shipping agent identity products; the IETF has not finished the standard.” https://forkast.news/six-vendors-are-shipping-agent-identity-products-the-ietf-has-not-finished-the-standard/ ↩ vLLM, “vLLM Semantic Router v0.1 Iris: The First Major Release,” 5 January 2026. https://vllm.ai/blog/2026-01-05-vllm-sr-iris; https://github.com/vllm-project/semantic-router ↩ CNCF, “Welcome llm-d to the CNCF,” 24 March 2026. https://www.cncf.io/blog/2026/03/24/welcome-llm-d-to-the-cncf-evolving-kubernetes-into-sota-ai-infrastructure/ ↩ agentgateway. https://agentgateway.dev/blog/2026-08-03-new-mcp-spec-revision/ ↩ Microsoft Azure, “The economics of agent optimization.” https://azure.microsoft.com/en-us/blog/the-economics-of-agent-optimization-how-ai-agent-governance-controls-cost-and-proves-roi/ ↩ Temporal, “Production-ready agents with the OpenAI Agents SDK + Temporal.” https://temporal.io/blog/announcing-openai-agents-sdk-integration; Temporal docs. https://docs.temporal.io/develop/python/integrations/openai-agents-sdk ↩ Forkast, “Durable execution is the next agent infrastructure sub-sector” (Restate under BSL 1.1, Inngest under SSPL 1.0). https://forkast.news/durable-execution-is-the-next-agent-infrastructure-sub-sector ↩ Red Hat Developer, “Standardize project context with AGENTS.md and Agent Skills,” 27 July 2026. https://developers.redhat.com/articles/2026/07/27/standardize-project-context-agentsmd-and-agent-skills; Harness, “The agent-native repo.” https://www.harness.io/blog/the-agent-native-repo-why-agents-md-is-the-new-standard ↩ Atlan, “How to choose an agentic framework for the enterprise.” https://atlan.com/know/ai-agent/how-to-choose-agentic-framework-enterprise/ ↩ Snowflake Engineering, “Operationalizing Data Interoperability in Multi-Engine Lakehouses.” https://www.snowflake.com/en/blog/engineering/lakehouse-data-interoperability-guide/ ↩ OpenTelemetry, GenAI semantic conventions repository (the conventions moved here from the core semantic-conventions docs). https://github.com/open-telemetry/semantic-conventions-genai; Dash0, “OpenTelemetry GenAI semantic conventions explained.” https://www.dash0.com/knowledge/opentelemetry-genai-semantic-conventions-explained ↩ InfoWorld, “The Microsoft agent framework wars are over; the real architecture decision starts now.” https://www.infoworld.com/article/4199575/the-microsoft-agent-framework-wars-are-over-the-real-architecture-decision-starts-now.html ↩ MarkTechPost, coverage of GitHub Agent HQ (launched February 2026 with Claude and Codex). https://www.marktechpost.com/2026/06/10/ai-coding-agents-development-platforms-2026/ ↩ Lines & Circles, “Enterprise Agent Platforms 2026: Gemini, Agentforce, Bedrock.” https://linesncircles.com/Blog/Enterprise/Enterprise_Agent_Platforms_2026 ↩ Gartner, “Gartner Identifies the Top Strategic Trends in Software Engineering for 2025 and Beyond,” 1 July 2025. https://www.gartner.com/en/newsroom/press-releases/2025-07-01-gartner-identifies-the-top-strategic-trends-in-software-engineering-for-2025-and-beyond ↩ Gartner, “Gartner Predicts 60% of Organizations Will Adopt Smaller Software Engineering Teams by 2029,” 7 July 2026. https://www.gartner.com/en/newsroom/press-releases/2026-07-07-gartner-predicts-60-percent-of-organizations-will-adopt-smaller-software-engineering-teams-by-2029 ↩ Gartner, “Gartner Says the Market for Enterprise AI Coding Agents Is Entering a New Phase of Expansion and Competitive Realignment,” 20 May 2026. https://www.gartner.com/en/newsroom/press-releases/2026-05-20-gartner-says-the-market-for-enterprise-ai-coding-agents-is-entering-a-new-phase-of-expansion-and-competitive-realignment ↩ --- # The Memory Hierarchy: Data Architectures Beyond Naive Disaggregation URL: https://platformatory.io/blog/where-should-your-data-live/ Published: 2026-11-17 Authors: Pavan Keshavamurthy Categories: Storage, Distributed Systems, Infrastructure, Kafka, Platform Engineering “Local NVMe or object storage?” sets up a binary that every storage system has already dissolved: each one is a memory hierarchy.1 Three decisions remain. Which tier holds the truth, which tiers cache it, and what a miss costs at each boundary, in time and in money.   Local-disk design Object-store design Hot reads RAM → local NVMe RAM → local NVMe cache Miss Local NVMe, µs Object store, 100–200 ms (standard) or single-digit ms (one-zone)23 Durable commit Replicate across zones, then ack Write to the object store, then ack Source of truth Replicated local disks Object store Weak spot Fixed capacity, slow rebuilds Tail latency, cold caches Same working set, one round trip per durable write. They differ in where truth lives, what a miss costs, and what capacity and recovery cost. Every tier becomes a cache DRAM caches disk; disk once cached tape. SSDs made the network the bottleneck of network storage. Now local NVMe caches object storage. Each tier down is roughly ten times slower and buys capacity, durability, elasticity or a lower price per GB. Put each byte on the cheapest tier that meets its latency budget, and make misses rare and cheap. Our napkin-math table has the numbers. When to cache has had a formula since 1987, the five-minute rule.4 Keep a page in the faster tier if it’s re-read within the break-even interval: \[T = \frac{\text{pages per MB of RAM}}{\text{accesses per second per disk}} \times \frac{\text{price per disk}}{\text{price per MB of RAM}}\] Recomputed in 2019 for 4 KB pages, DRAM over SSD came out at five minutes, DRAM over HDD at four hours, and newer non-volatile memory at under a minute.4 The cloud version swaps device prices for a bill. A local copy costs rent; a miss costs a GET. Re-reading an object of size \(s\) more often than every \[T = \frac{\text{price per GET}}{\text{cache price per GB-second} \times s}\] makes the cached copy cheaper, before counting latency. At S3 Standard’s $0.0004 per 1,000 GETs, with gp3 block storage at $0.08 per GB-month standing in for cache rent (AWS US East list prices throughout):56 Object size Cache it if re-read within 4 KB about 37 days 1 MB about 3.6 hours 64 MB about 3.4 minutes Small objects and metadata: cache everything, because requests dominate the bill. Large segments read less often than every few minutes: leave them in the store. Latency only pushes the line towards caching more, and so does the stand-in: gp3 is conservative, and instance NVMe, bundled with the instance, makes caching pay off sooner. Reads: the working set decides flowchart LR Q[Query] --> RAM{In RAM?} RAM -- hit --> A1[~100 ns] RAM -- miss --> NVME{On local NVMe?} NVME -- hit --> A2[~10s of µs] NVME -- miss --> SRC[Source of truth] SRC --> L[Replicated local diskor network block storage~sub-ms] SRC --> O[Object storagesingle-digit ms one-zone100–200 ms standard] Working set Implication Fits in RAM Storage tier barely matters Fits local NVMe but overflows RAM Local flash decides; either design provides it Wide and random (big keyspace, cold scans) Misses dominate p99 and p999; local NVMe’s flat tail wins The metric that matters is the hit ratio at each tier boundary. Instance type follows from it. The local NVMe tier is bigger and faster than most designs assume. Flash costs under $200 per TB, 10 to 50 times less than DRAM, and a PCIe 4.0 SSD does over a million random 4 KB reads per second at 7 GB/s.7 Spend the same money two ways on a $15,000 server:7 Configuration RAM Flash Bandwidth All RAM 2.5 TB None 150 GB/s from RAM RAM plus SSDs 0.5 TB 8 × 4 TB 150 GB/s from RAM, 56 GB/s from flash Eight SSDs measured 12.5 million random reads per second. Five storage engines on the same box (RocksDB, WiredTiger, PostgreSQL, MySQL and LeanStore as first built) reached a fraction of that; the best managed 3.6 million.7 The hardware outran the software. Little’s law says why. Flash answers a random read in about 100 µs, so \[\text{IOPS} = \frac{\text{I/Os in flight}}{\text{latency}}\] and a thread that waits for each read gets 10,000 IOPS. Saturating the array takes about 1,000 reads in flight, more than 100 per device. At 12 million IOPS a 64-core server has some 13,000 CPU cycles per I/O, half of it spent just issuing and completing the request, unless the kernel is bypassed.7 Engines that reach the hardware share a design: Asynchronous I/O issued by the worker threads themselves: io_uring, libaio or kernel-bypass SPDK; all three can saturate the drives, and SPDK spends the least CPU doing it. Lightweight user-space threads, so one core can switch between thousands of outstanding requests instead of blocking. 4 KB pages: the best balance of IOPS, latency and amplification on flash. Smaller pages got slower, larger ones amplify. Out-of-memory paths treated as hot: eviction partitioned to handle tens of millions of pages a second. Built that way, LeanStore ran TPC-C at 1.1 million transactions a second with data ten times the size of its 400 GB buffer pool, and 400,000 a second at forty times.7 Mixed reads and writes cut the array to 6.7 million IOPS, since flash writes cost about ten times as much as reads. So a working set that fits local NVMe but overflows RAM can run close to in-memory speed, if the engine keeps enough I/O in flight. Check that before buying RAM, or before deciding the local tier is too slow and moving the truth to a slower one. Writes: durability costs one round trip sequenceDiagram participant C as Client participant P as Primary participant R as Replica (other AZ) participant S as Object store Note over C,R: Local-disk design C->>P: commit P->>R: replicate R-->>P: ack P-->>C: ack (one cross-AZ round trip) Note over C,S: Object-store design C->>P: commit P->>S: PUT (batched) S-->>P: ok P-->>C: ack (one object-store write) One cross-zone round trip against one object-store write. Latency favours replication: a standard object-store write takes on the order of 100 ms, and the one-zone classes that reach single-digit milliseconds give up multi-zone durability.23 Cost can favour the store, depending on batch size. Replicating to two other zones costs $0.01 per GB out and $0.01 in, per copy: $0.04 per GB written.8 A PUT costs $0.005 per 1,000 whatever its size,5 so per GB the object store costs \(\frac{\$0.000005 \times 10^9}{b}\) for batches of \(b\) bytes: AWS US East list prices: $0.005 per 1,000 PUTs; $0.01 per GB each way across zones. The break-even batch is about 125 KB, and filling it takes time: \(b\) divided by the writer’s throughput. A writer producing 1 MB/s waits 125 ms per batch; at 10 MB/s, 12.5 ms. Object-store-first wins on cost for high-volume, log-shaped data, and pays for it in latency on low-volume streams. Storage rent tilts it further. S3 Standard costs about $0.023 per GB-month; three replicas on gp3 cost about $0.24, ten times as much, and for long retention that outweighs every write-path term above.56 The sums still leave out consumer GETs and the producer’s own hop across zones. Object storage is the best bottom tier. What it gives: Managed multi-zone durability. A small, immutable interface that pushes designs towards logs, now with conditional writes: If-None-Match since August 2024 and If-Match since November 2024, enough for writer fencing.9 Elastic capacity, cheap per GB and costly per request. Recovery by warming a cache, with no data to copy. What you still own: Cache sizing, eviction and cold restarts, which usually arrive mid-incident. Metadata: the object set, ordering and writer fencing, typically backed by consensus. Compaction and garbage collection, or read amplification and a large bill. The miss path: S3 scales to at least 3,500 writes and 5,500 reads per second per prefix, returning 503s while it scales up.2 Throttling shows up in the tail. Capacity and durability get simpler. The system doesn’t: on-call moves to the cache and metadata layers. Streaming systems have already made this move. We operate self-hosted Kafka, Flink and related data infrastructure for customers as a managed service, so we have a stake in where its data lives. Tiered storage (KIP-405): hot segments local, cold segments in object storage. Early access in Kafka 3.6, production-ready in 3.9.10 Diskless topics (KIP-1150) and object-store-native Kafka-compatible systems: the write path on object storage, trading produce latency for no cross-zone replication traffic and nearly stateless brokers. KIP-1150 was accepted in March 2026; its core design, in KIP-1163 and KIP-1164, was still under discussion in August 2026, with no release named.1112 Choose per workload: Workload Latency budget Source of truth Payments, orders, control plane Low tens of ms, tight p99 Replicated local disks, tiered history CDC into analytics Seconds Tiered or diskless, by volume Logs, metrics, clickstream Seconds to minutes Object storage first Long-term replay Throughput Object storage behind a cache Checklist Working set against RAM and NVMe per node, measured. Miss rate at each tier boundary, and the latency behind it. I/Os in flight per NVMe device, the I/O interface, and page size: whether the engine can reach the drives at all. The p99 and p999 budget. Round trips per durable write, and how much batching the budget tolerates. Recovery: rebuild from peers or warm from the store, how long, and how degraded meanwhile. Cost: IOPS caps, provisioned throughput, cross-zone transfer, per-request charges, and the break-even object and batch sizes above. Who owns the cache, the metadata and compaction. Miss-heavy OLTP belongs on local NVMe; high-volume logs belong in cached object storage. Durability costs one round trip either way: a few milliseconds across zones, or about 100 ms to a standard object store. Pick the tier that holds the truth, cache the rest, and keep misses rare and cheap. Thread on X. https://x.com/jorandirkgreef/status/2118057836207104173 ↩ AWS, “Best practices design patterns: optimizing Amazon S3 performance” (at least 3,500 PUT and 5,500 GET requests per second per prefix; 503 Slow Down while scaling; small-object latencies of roughly 100–200 ms). https://docs.aws.amazon.com/AmazonS3/latest/userguide/optimizing-performance.html ↩ ↩2 ↩3 AWS, “Amazon S3 Express One Zone” (single-digit millisecond access, single Availability Zone). https://aws.amazon.com/s3/storage-classes/express-one-zone/ ↩ ↩2 Raja Appuswamy, Goetz Graefe, Renata Borovica-Gajic and Anastasia Ailamaki, “The Five-Minute Rule 30 Years Later and Its Impact on the Storage Hierarchy,” Communications of the ACM 62(11), November 2019. https://doi.org/10.1145/3318163 ↩ ↩2 AWS, “Amazon S3 pricing,” US East (N. Virginia), S3 Standard: $0.005 per 1,000 PUT requests, $0.0004 per 1,000 GET requests. https://aws.amazon.com/s3/pricing/ ↩ ↩2 ↩3 AWS, “Amazon EBS pricing,” US East (N. Virginia), gp3: $0.08 per GB-month. https://aws.amazon.com/ebs/pricing/ ↩ ↩2 Gabriel Haas and Viktor Leis, “What Modern NVMe Storage Can Do, And How To Exploit It: High-Performance I/O for High-Performance Storage Engines,” PVLDB 16(9), 2090–2102, 2023. https://www.vldb.org/pvldb/vol16/p2090-haas.pdf ↩ ↩2 ↩3 ↩4 ↩5 AWS Architecture Blog, “Exploring Data Transfer Costs for AWS Managed Databases” (cross-AZ traffic charged $0.01 per GB in each direction). https://aws.amazon.com/blogs/architecture/exploring-data-transfer-costs-for-aws-managed-databases/ ↩ AWS, “Amazon S3 now supports conditional writes,” 20 August 2024; “Amazon S3 adds new functionality for conditional writes,” 25 November 2024. https://aws.amazon.com/about-aws/whats-new/2024/08/amazon-s3-conditional-writes; https://aws.amazon.com/about-aws/whats-new/2024/11/amazon-s3-functionality-conditional-writes ↩ Apache Kafka, “Apache Kafka 3.9.0 Release Announcement,” 6 November 2024. https://kafka.apache.org/blog/2024/11/06/apache-kafka-3.9.0-release-announcement/ ↩ Aiven, “KIP-1150 accepted, and the road ahead,” 12 March 2026. https://aiven.io/blog/kip-1150-accepted-and-the-road-ahead ↩ SoftwareMill, “Diskless Kafka: object storage, KIP-1150 and Kafka’s future,” August 2026; Apache Kafka wiki, “KIP-1163: Diskless Core.” https://softwaremill.com/diskless-kafka-object-storage-kip-1150-and-kafkas-future/; https://cwiki.apache.org/confluence/display/KAFKA/KIP-1163:+Diskless+Core ↩ --- # Oracle CDC with XStream and Debezium, Revisited: Where Changes Wait URL: https://platformatory.io/blog/oracle-cdc-revisited/ Published: 2026-11-14 Authors: Pavan Keshavamurthy Categories: Kafka, CDC, Oracle, Connectors, Data Streaming Moving Oracle changes into Kafka sounds simple: capture committed changes and publish them as events. We’ve written about doing it with Debezium and LogMiner, with OpenLogReplicator, and with Confluent’s Oracle CDC connector. Since then the ground has shifted. Debezium’s Oracle connector now offers four capture paths, Confluent ships a second Oracle connector built on XStream, and the question has moved from “how do we set it up?” to “why is it three hours behind?” The setup is the easy part. A pipeline that moves 100,000 events a second in a benchmark can still fall hours behind at month-end, or take a day to recover from an outage. What decides throughput, lag and cost is where changes wait, how much spare capacity sits behind each wait, and who pays for the capture engine. What happens between an Oracle commit and a Kafka event? With XStream, seven stages: Redo: Oracle writes every change to the online redo logs, then archives them. Capture: a capture process mines the redo and turns changes into logical change records (LCRs).1 Buffered queue: LCRs wait in SGA memory, in the Streams pool, until their transaction commits. They spill to disk when they’ve waited too long, when a transaction holds too many, or when memory runs short.1 Outbound server: assembles committed transactions and streams them to one attached client.1 Connector: Debezium, or Confluent’s connector built on it,2 turns LCRs into Kafka records and buffers them in a queue for Kafka Connect. Producer: batches, compresses and sends. Broker: replicates and acknowledges. The client acknowledges progress by reporting a processed low position: the point below which every transaction has been handled. The outbound server keeps its own copy, updated on a timer (30 seconds by default for OCI clients), so after a restart it resends whatever it can’t prove was processed, and the client must discard the duplicates.1 Delivery into Kafka is at-least-once; Confluent’s documentation says so plainly.2 Consumers should be idempotent on the row key and the change’s SCN. Each stage has its own capacity, buffer and failure mode, and each exposes a number that says whether it’s keeping up. Diagnosing lag means reading those numbers in order. Scaling Oracle, Connect or Kafka at random only moves money. Where do open transactions wait? This is the question the choice of capture path really answers. Oracle can only publish a transaction once it commits, so something has to hold the changes of every open transaction until then. The four paths put that something in different places:3 Capture path Where open transactions wait What breaks first under a long transaction Extra Oracle licence LogMiner, buffered (Debezium’s default) Connector JVM heap, or a disk-backed Infinispan or Ehcache buffer Heap; the mining window can’t advance past the oldest open transaction No LogMiner, unbuffered Oracle PGA, since LogMiner returns committed changes only PGA_AGGREGATE_LIMIT errors on large transactions No OpenLogReplicator A separate process that reads redo files directly That process’s memory; little load on the database No XStream The Streams pool in Oracle’s SGA, spilling to disk Streams pool pressure, then spill I/O Yes: XStream is part of Oracle GoldenGate4 The table also explains why “LogMiner versus XStream” benchmarks diverge so widely. They mostly measure where a long transaction lands. LogMiner’s CONTINUOUS_MINE option, which older tools relied on to follow log switches, was removed in Oracle 19c, so LogMiner-based connectors now track log switches themselves.5 What’s the trade between throughput and latency? Batching amortises serialisation, network round trips, compression and producer overhead across more events, and every batch makes something wait. Two relationships bound the trade. The first is plain arithmetic: \[\text{backlog growth} = \lambda - \mu\] where \(\lambda\) is the rate changes arrive and \(\mu\) the rate the slowest stage can process them. If \(\lambda > \mu\) for long, lag grows without limit, and no buffer size fixes it. The second is Little’s law: \[L = \lambda W\] Events in flight equal throughput times average residence time. At 10,000 events a second and two seconds in the pipeline, 20,000 events are in flight; at 100 ms, 1,000. How close to its capacity a stage runs also sets its wait. In the simplest queueing model, one server with random arrivals, time in the system is \(S/(1-\rho)\) for service time \(S\) and utilisation \(\rho\): twice the service time at 50% busy, five times at 80%, ten times at 90%. Real pipelines aren’t that simple, but the shape holds: a stage run hot turns small bursts into long waits. How much headroom does recovery need? More than most teams provision. After an outage of length \(D\), the backlog is \(\lambda D\), and it drains at \(\mu - \lambda\) while new changes keep arriving. With headroom \(h = \mu/\lambda\): \[T_{\text{drain}} = \frac{\lambda D}{\mu - \lambda} = \frac{D}{h - 1}\] For a one-hour outage, catching up takes four hours at 1.25× headroom, two at 1.5×, one at 2×, and 15 minutes at 5×: Assumes a one-hour outage, with arrivals continuing at the same rate during the catch-up. A pipeline sized at 1.25× peak looks healthy every day and takes four hours to recover from a one-hour outage, longer if the outage hit at peak. An SLO that promises recovery from a one-hour outage within 15 minutes is a promise of 5× headroom at the slowest stage. Say that before signing it. Recovery also needs the redo to still exist. Capture restarts from the required checkpoint SCN, and every redo log from there on must be available.1 Archive retention has to cover the outage, the drain, and the age of the oldest open transaction, which holds the restart point back. At an illustrative 50 MB/s of redo, an hour’s outage and 15 minutes’ drain need 225 GB of archived logs on hand, before any long transaction stretches it. Is Oracle or Kafka the bottleneck? Neither, by default. The stage whose backlog grows is the constraint: Observation Likely constraint Capture falls behind redo generation Mining: CPU, redo I/O, transaction reconstruction Capture keeps up; the outbound low watermark lags XStream delivery, or backpressure from the connector The connector’s queue sits near full Record conversion in Connect, or Kafka publishing Producer request latency rises Brokers, network, replication or producer settings Every stage keeps up; consumer lag rises The downstream consumer Redo throughput and event throughput are different measurements. Oracle can write a lot of redo for changes that yield few events (index maintenance, uncaptured tables, LOB churn), and supplemental logging adds redo of its own. Compare captured LCRs per second with Kafka records per second; redo against records compares unlike things. How should XStream’s memory be sized? Three settings, all in Oracle: STREAMS_POOL_SIZE: the shared pool XStream draws on. Oracle requires at least 300 MB, and recommends setting it explicitly rather than leaving it to automatic memory management.6 Left unset with automatic management off, the pool takes 10% of the shared pool on first use.7 Capture MAX_SGA_SIZE: the capture process’s share of the pool.6 Outbound MAX_SGA_SIZE: the outbound server’s share. The sum of every component’s limit must stay below the pool size.6 Oracle prescribes no ratio between capture and outbound. Equal shares are a sensible start; give capture more when transaction reconstruction dominates, and outbound more when delivery does, and decide from measured use and spill rather than by rule. Two apply parameters, txn_lcr_spill_threshold and txn_age_spill_threshold, set when LCRs spill, and Oracle notes that an outbound server performs best when few do.1 Capture PARALLELISM defaults to 0 for XStream Out, one process doing all the mining; raising it adds reader, preparer and builder processes.1 More memory helps only when memory is the constraint. It can’t buy CPU, faster redo reads or a faster Kafka cluster. Why do long transactions matter so much? A transaction that starts at 10:00 and commits at 10:30 can’t be published at 10:01, however quickly its redo was mined. For thirty minutes something holds its changes, and on every path above, that something is finite. Meanwhile the restart point can’t advance past it, so redo retention stretches with it. The leading indicator is the age of the oldest open transaction that capture is tracking. Debezium’s LogMiner adapter exposes it as OldestScnAgeInMilliseconds, alongside NumberOfActiveTransactions.3 Age alone misleads: a two-hour idle transaction and a five-minute one that updates ten million rows stress different things. Track the largest open transaction by LCRs or bytes too, and keep database-wide open transactions apart from the ones capture actually follows. Two Debezium escape valves deserve care. log.mining.window.max.ms lets the mining window advance past a transaction that’s been open too long, while still tracking it. log.mining.transaction.retention.ms discards transactions open longer than its value, and their changes are never emitted.3 The first trades memory for complexity; the second trades it for data loss. Which Oracle-side settings matter most? Roughly in order: Capture scope: capture only the schemas and tables you need; everything else is redo decoded for nothing. Supplemental logging: log the key columns correctness needs, and no more.6 Streams pool and process memory: sized against measured use and spill. Redo and archive I/O: enough for peak generation and for catch-up reads at the same time. Transaction shape: the application’s batch jobs, purges and forgotten sessions. Retention: archives kept for the recovery window above. RAC topology: capture follows the queue’s owning instance; set USE_RAC_SERVICE.1 Confluent reports persistent throughput drops after RAC failover on Oracle 19.30 and 19.31, which it attributes to an Oracle defect.8 Then measure, change one thing, and measure again under the same workload. How much does the connector’s configuration matter? Less than its reputation, as long as nothing downstream is saturated. Debezium’s main dials, with their defaults:3 max.batch.size (2,048): the most records handed to Connect per iteration. It’s a ceiling: a batch returns before it fills, so raising it adds no wait. max.queue.size (8,192): the records buffered between the capture thread and Connect. Keep it larger than the batch size; max.queue.size.in.bytes adds a byte cap for wide rows and LOBs. poll.interval.ms (500): how long each iteration waits for new events. Not Oracle’s mining interval. heartbeat.interval.ms (0, off): heartbeats keep offsets moving on quiet tables. Confluent recommends minutes to hours for its connector.2 On the producer, linger.ms now defaults to 5 ms, not 0, since Kafka 4.0, because larger batches usually mean similar or lower latency.9 Compression and acks trade CPU, bandwidth and durability against latency. A bigger queue absorbs a burst; it doesn’t make a saturated stage faster. And some latency isn’t configurable: Confluent’s documentation notes about three seconds of extra latency when the database is quiet, from XStream’s own batching.2 Is Confluent’s XStream connector faster than Debezium’s? The public evidence can’t say. Confluent’s connector is built on Debezium and Kafka Connect, and both use the same XStream outbound server.2 Confluent claims two to three times the throughput and latency of “traditional CDC approaches”,10 meaning LogMiner. The benchmarks sit in a gated whitepaper, and they compare XStream with LogMiner. Neither says anything about one XStream connector against another. A fair head-to-head holds constant the Oracle version and workload, XStream settings, Kafka cluster and replication, serialisation, compression and acks, connector resources, transaction sizes and concurrency, and the starting backlog. Then the differences that remain (LCR conversion, allocation, buffering, checkpointing, restart) can show up, and their size will depend on the workload. The licensing difference is clearer than the performance one, and larger. XStream is licensed as part of Oracle GoldenGate, which in turn requires Enterprise Edition.4 Debezium’s XStream adapter needs that licence. Confluent’s connector includes it, under an agreement with Oracle, in its own subscription.2 So the honest comparisons are a Confluent subscription against a GoldenGate licence plus running Debezium yourself, or against LogMiner or OpenLogReplicator, which need no extra Oracle licence and leave the long-transaction problem in your connector. Confluent’s connector has XStream’s limits too: one outbound server per connector, since a server accepts one client; one pluggable database per connector; no capture on a Data Guard standby, where downstream capture is the workaround.2 What should a CDC service level measure? One “lag” number won’t do. Four dimensions: Dimension Measures Freshness p50, p95 and p99 commit-to-Kafka latency; age of the oldest committed change not yet in Kafka Capacity Redo MB/s; LCRs per second; Kafka records per second; measured maximum rate, giving headroom Pressure Capture and outbound progress; queue depth; spill; Streams pool use; oldest open transaction Recovery Redo retained against redo required; checkpoint age; restart time; drain rate SCN differences aren’t seconds; convert through commit timestamps. And the age of the last processed event misreports freshness when tables are idle or a long transaction is open, which is what heartbeats are for. A useful SLO names both steady state and recovery: 99% of committed changes visible in Kafka within five seconds at the agreed peak, and recovery from a one-hour outage within 15 minutes. By the drain arithmetic, the second clause costs 5× headroom, and it’s often the clause worth negotiating. What does reliable Oracle CDC cost? \[\text{cost} = \text{licences} + \text{infrastructure} + \text{operations} + \text{incidents and recovery}\] Licences are Oracle’s (Enterprise Edition and GoldenGate, for XStream) and the connector’s. Infrastructure is database CPU and memory for capture, archive storage for retention, Connect workers, and Kafka capacity sized for the drain rather than the average. Operations is the people who understand capture, the Streams pool and Kafka at once, on call around the clock. A free connector gets expensive when every long transaction becomes a page; a subscription doesn’t pay for itself by including support. We operate self-hosted Kafka, Flink and related data infrastructure for customers as a managed service, and predictability is worth more than peak throughput there. So what’s the right architecture? Start from the business requirement: how fresh, at what peak, recovered how fast. Translate it into headroom with the drain formula. Pick the capture path by where you can afford open transactions to wait and what you’re licensed for. Size Oracle and Kafka separately, instrument every boundary in the pipeline, and test the cases that hurt: a long transaction, a burst, a slow broker, a restart after an hour down. Use open-source Debezium where it meets the workload and you can run it. Pay for a commercial connector when its measured behaviour, support or bundled licence beats the alternative on that test. Its own benchmark settles nothing. Oracle, XStream Guide 19c, “XStream Out Concepts” (capture process, LCRs, buffered queue and spill, outbound server and single client session, processed low position and acknowledgement interval, checkpoints and required checkpoint SCN, PARALLELISM, USE_RAC_SERVICE). https://docs.oracle.com/en/database/oracle/oracle-database/19/xstrm/xstream-out-concepts.html ↩ ↩2 ↩3 ↩4 ↩5 ↩6 ↩7 ↩8 Confluent, “Oracle XStream CDC Source Connector for Confluent Platform” (built on Debezium and Kafka Connect; at-least-once delivery; XStream licence included; limitations; heartbeat and quiet-database latency notes). https://docs.confluent.io/kafka-connectors/oracle-xstream-cdc-source/current/overview.html ↩ ↩2 ↩3 ↩4 ↩5 ↩6 ↩7 Debezium documentation 3.7, “Debezium connector for Oracle” (adapters, buffer types, log.mining.window.max.ms, log.mining.transaction.retention.ms, queue and batch defaults, streaming metrics). https://debezium.io/documentation/reference/stable/connectors/oracle.html ↩ ↩2 ↩3 ↩4 Oracle GoldenGate Licensing Information (a GoldenGate licence includes Oracle XStream; Enterprise Edition is a prerequisite). https://docs.oracle.com/en/middleware/goldengate/core/23/ogglc/oracle-goldengate.html ↩ ↩2 Oracle Database PL/SQL Packages and Types Reference 19c, “DBMS_LOGMNR” (CONTINUOUS_MINE desupported in 19c). https://docs.oracle.com/en/database/oracle/oracle-database/19/arpls/DBMS_LOGMNR.html ↩ Oracle, XStream Guide 19c, “Configuring XStream Out” (Streams pool of at least 300 MB, max_sga_size for capture and outbound, supplemental logging). https://docs.oracle.com/en/database/oracle/oracle-database/19/xstrm/configuring-xstream-out.html ↩ ↩2 ↩3 ↩4 Oracle Database Reference 21c, “STREAMS_POOL_SIZE.” https://docs.oracle.com/en/database/oracle/oracle-database/21/refrn/STREAMS_POOL_SIZE.html ↩ Confluent Support, “Why does Oracle XStream CDC Source Connector throughput drop after RAC failover.” https://support.confluent.io/hc/en-us/articles/52668236858260-Why-does-Oracle-XStream-CDC-Source-Connector-throughput-drops-after-RAC-failover ↩ Apache Kafka, “KIP-1030: Change constraints and default values for various configurations” (linger.ms default from 0 to 5 in 4.0). https://cwiki.apache.org/confluence/display/KAFKA/KIP-1030:+Change+constraints+and+default+values+for+various+configurations ↩ Mac Khajuria and Sudhindra Sheshadrivasan, “Meet the Oracle XStream CDC Source Connector,” Confluent blog, 19 March 2025. https://www.confluent.io/blog/oracle-xstream-cdc-connector/ ↩ --- # Running a Private AI Estate: Self-Hosting LLMs from One GPU to a Cluster URL: https://platformatory.io/blog/self-hosting-llms-air-gapped/ Published: 2026-11-11 Authors: Pavan Keshavamurthy Categories: AI, Kubernetes, Platform Engineering, Infrastructure Work your way out of GPU poverty and the same question arrives at every team: can we serve intelligence ourselves, as a service, to everyone who needs it, air-gapped if we have to? Appliances are back, this time shipping with a model, and the hardware is a purchase order: tinybox (2024): multi-GPU machines in one chassis, from $15,000 at launch.1 DGX Spark (October 2025): book-sized, 128 GB of memory shared by CPU and GPU, a 240 W power supply, $3,999 at launch.23 At any non-trivial scale the economics of self-hosting can be compelling. How compelling depends on the class of model, on whether you train, serve or both, and on what the intelligence is for; Too Cheap to Meter works through that case. Here we take the case as made and work through the how, from one box on a desk to clusters that serve and train across racks. We followed the question through, and each answer raised the next question. What will it actually run? The first surprise is that compute isn’t the constraint. Each generated token reads the model’s active weights from memory once, so single-stream speed has a hard ceiling: \[\text{tokens/s} \;\le\; \frac{\text{memory bandwidth}}{\text{bytes read per token}}\] Desktop appliances have plenty of capacity and little bandwidth: 273 GB/s on the Spark, about a twelfth of a datacentre H100’s 3.35 TB/s.24 On that box: Llama 3.1 70B, FP8 (70 GB read per token): ceiling \(273/70 \approx 3.9\) tokens/s; measured 2.7, against 803 tokens/s of prefill.5 Llama 3.1 8B, FP8: 20.5 tokens/s for one user, 368 aggregate across a batch of 32.5 gpt-oss-120b, MXFP4: 117B parameters, about 5.1B active per token at 4.25 bits, roughly 2.7 GB read per token; ceiling around 100 tokens/s.6 So the answer is: big models that touch little per token. Mixture-of-experts models fit a capacity-rich, bandwidth-poor machine; dense giants fit and crawl. 273 GB/s of unified memory. Measured values from October 2025;5 ceilings from the arithmetic above. Can it make the model ours, by fine-tuning on our own data? Partly. Training holds far more in memory than serving does: Full fine-tuning, 16-bit: weights, gradients and optimizer state at once, more than 780 GB for a 65B model, so \(780/65 \approx 12\) bytes per parameter.7 128 GB covers roughly \(128/12 \approx 10\)B parameters, before activations. QLoRA: a frozen 4-bit model plus small trained adapters; 65B fits in under 48 GB.7 The “fine-tune 70B” headline assumes this. Adapters are the realistic path: your documents, tools and tone layered onto an open model. And a box that’s training is a box that isn’t serving, which is the first hint that one machine will have more than one job. What if one box isn’t enough? Link two, and the network sets the pace: a 200 Gb/s port moves 25 GB/s, a tenth of the memory bandwidth inside each box.2 Distributed inference turns up on a desk. How do we know it’s good enough? “Fast enough” has to become numbers before anyone depends on the box. For inference: TTFT and ITL (time to first token, inter-token latency) at p50 and p95: what users feel as responsive and fluent. Goodput: requests or tokens per second inside both latency targets. Peak throughput with latency ignored is a vanity number. Concurrency: users or agents sustained before targets break. Tokens per joule and cost per million tokens, at the wall plug. Software counters on unified memory are incomplete; nvidia-smi on the Spark reports no memory use at all.8 Quality on your own tasks: a quantised model twice as fast that fails your evaluation set is a regression. For fine-tuning: training tokens per second, time to converge on your data, and the result on the same evaluation set. The tools are free: GuideLLM for request-rate sweeps,9 vLLM’s bench serve, and NVIDIA’s AIPerf for realistic arrival patterns.10 Their metric definitions differ, so compare within one tool.11 And is it really “at the cost of power”? Electricity per million tokens, for a box drawing \(P\) kW at \(c\) dollars per kWh and producing \(r\) tokens per second: \[C_{10^6} = \frac{P \cdot c}{3600\, r} \times 10^{6}\] With \(P = 0.24\) (full draw) and \(c = 0.15\) (illustrative), that’s 3.6 cents an hour: Dense 70B, one user (2.7 tokens/s): about $3.70 of electricity per million tokens 8B, one user (20.5 tokens/s): about $0.49 8B, batch of 32 (368 tokens/s): under 3 cents Hardware: $3,999 over three years is about 15 cents an hour, four times the electricity Power is the small line, and the spread across workloads is 136-fold on the same box. The cost per token is decided by model choice and batching, and batching means many users. Illustrative: 240 W at full draw, $0.15/kWh, $3,999 over three years. So how do we run it, once other people depend on it? Every answer so far points the same way. Good economics need batching, so many users. Making the model ours means fine-tuning, so a second workload. Measuring needs benchmarks, a third. Big models need a second box. And the air-gap means every image, driver, weight and update arrives by one audited path. The box has turned into a small fleet with shared GPUs. Three ways to run that, each right for someone: Option Fits Strains when A single model server (Ollama, llama.cpp, or vLLM in a container) One person, one model, quick experiments A second user needs queueing, a second model needs the GPU, or updates have to be audited A compose file of services on one box A small team sharing one box A second box arrives, jobs compete for GPUs, or you need rolling updates A small Kubernetes distribution with the GPU Operator Several workloads, several boxes, controlled air-gapped updates There’s one box and one user, or the hardware is so new the GPU tooling lags For one person experimenting, the single server wins: it answers in ten minutes, and Kubernetes would cost more than it saves. A compose file stretches surprisingly far on one box. Kubernetes has real costs, machinery to learn and run, and GPU tooling that trails brand-new desktop parts. But each requirement the simple options lack has to be built by hand: a scheduler for shared GPUs, an update mechanism, an air-gap procedure, a way to reproduce the box. Kubernetes already has them as a durable primitive: declarative deployments, GPU scheduling, health checks, operators. Past the second user, workload or box, it’s the cheaper path. (We build platforms on Kubernetes for customers, so we have a stake in this answer.) The pieces exist, air-gapped included: Distribution: k3s and RKE2 both document air-gapped installs: images from a tarball or private registry, artifacts pre-downloaded, upgrades through the same registry.1213 GPUs: NVIDIA’s GPU Operator installs driver, container runtime and device plugin, and lists the Spark as supported.14 Community reports show device-plugin versions crashing or misallocating on unified memory, so pin and test.8 Serving: vLLM or SGLang as the engine; llm-d’s Kubernetes-native routing beyond one replica; LeaderWorkerSet when a model spans two linked boxes.15 Air-gap: a registry mirror for images, a model store for weights, one audited path in for updates, the same shape for every workload. What changes when the fleet becomes a cluster? Past a few boxes, the two workloads stop resembling each other. Serving is a service: many short requests, bound by latency, scaled out by adding replicas. Training is one synchronous computation spread over every GPU in the job, bound by throughput, and it fails as a unit. Both run on the same hardware hierarchy, and the hierarchy is the first constraint. H100 SXM figures;4 one 400 Gb/s link per GPU, as in Llama 3’s training cluster.16 Each step outward costs bandwidth: 3.35 TB/s of memory inside a GPU, 900 GB/s of NVLink between the GPUs of one server, 50 GB/s per GPU across the network. That’s an 18-fold drop at the edge of the server, and every parallelism scheme is a decision about which data crosses it. Llama 3 orders its four, from the inside out, as tensor, context, pipeline and data parallel, and keeps tensor parallelism, the chattiest, inside the eight NVLinked GPUs of one server.16 How is one model served across many GPUs? The request splits before the model does. Prefill reads the whole prompt in one pass and is bound by compute; decode emits one token at a time and is bound by memory bandwidth, which is why the Spark managed 803 tokens/s of prefill and 2.7 of decode. Then the model splits, in one of five ways: Data parallel: a whole copy of the model per GPU or server, with a load balancer in front. The default whenever the model fits. Tensor parallel: each layer’s matrices split across GPUs, with an all-reduce every layer. Fast inside a server; across servers vLLM’s documentation asks for InfiniBand and calls a fallback to TCP “not efficient”.17 Pipeline parallel: layers cut into stages, one per server, so only activations cross the network. vLLM’s recipe for a model larger than a server is tensor parallel within each server and pipeline parallel across them.17 Expert parallel: a mixture-of-experts model’s experts spread across GPUs, attention kept data-parallel, each token sent to the few experts it needs.17 Disaggregated prefill and decode: the two phases on separate GPU pools, each sized and split for its own bottleneck, with the KV cache shipped between them. DistServe served 7.4 times more requests within latency targets than colocated systems.18 Once the weights are split, the bottleneck moves to the KV cache, the attention state each sequence keeps for every token it has seen: \[\text{KV bytes per token} = 2 \times \text{layers} \times \text{KV heads} \times \text{head dim} \times \text{bytes per value}\] Llama 3 70B has 80 layers, 8 KV heads and \(8192/64 = 128\) dimensions per head.16 At 16 bits that’s \(2 \times 80 \times 8 \times 128 \times 2 \approx 0.33\) MB per token: 2.7 GB for an 8,000-token conversation, 43 GB for one at the full 128,000. An eight-GPU H100 server has 640 GB; 70 GB of FP8 weights leave about 570 GB, room for some 210 conversations of 8,000 tokens or 13 at full context, before activations. Cache memory, more than weights, sets concurrency, and concurrency sets the cost per token. So distributed serving is largely cache logistics: routing each request to the replica that already holds its prefix, offloading cold cache to CPU memory or disk, and moving cache from prefill to decode over RDMA.1519 How is a model trained across many machines? Memory forces the split before speed does. Mixed-precision training with Adam keeps 16 bytes per parameter: 16-bit weights and gradients, plus 32-bit copies of the weights, momentum and variance.20 QLoRA’s “more than 780 GB” for 65B was a floor. At 16 bytes, a 70B model needs 1.12 TB for its training state, fourteen 80 GB GPUs before a single activation; 405B needs 6.5 TB. So the state is sharded, each GPU holding a slice and gathering layers as it needs them (ZeRO, and PyTorch’s FSDP),20 and the model is split as for serving, with context parallelism added for long sequences.1621 The job is synchronous: every step waits for the slowest GPU, and one failure stops all of them. Even at the frontier the hardware delivers well under half its peak. Llama 3 405B trained at 38–43% model FLOPs utilisation on up to 16,000 H100s;16 Megatron-LM reached 52% on 3,072 GPUs in 2021.21 What runs all this on Kubernetes? Layer Serving Training Devices GPU Operator; Dynamic Resource Allocation, stable since Kubernetes 1.34, requests GPUs and NICs by attribute rather than count22 The same Network RDMA NICs (InfiniBand or RoCE) attached to pods, GPUDirect RDMA, NCCL The same, carrying far more Engine vLLM, SGLang, TensorRT-LLM PyTorch FSDP, Megatron-LM, DeepSpeed, JAX Unit of pods LeaderWorkerSet: a multi-host replica created, placed and restarted as one23; Grove’s PodCliqueSet for disaggregated roles24 JobSet: a group of Jobs recreated whole on failure, optionally one per rack25 Queues and gangs Shared with training when one cluster runs both Kueue: quotas, all-or-nothing admission, placement by rack or block26; KAI Scheduler: gangs, hierarchical queues, GPU sharing27; Volcano; Slurm on Kubernetes via Slinky28 Routing Gateway API Inference Extension: an InferencePool and an endpoint picker that routes on prefix cache and LoRA adapters29 Not applicable Platform llm-d: prefix-aware scheduling, disaggregation, wide expert parallelism, tiered KV cache15; NVIDIA Dynamo19; KServe’s LLMInferenceService, built on llm-d30 Kubeflow Trainer v2: a TrainJob over JobSet for PyTorch, DeepSpeed, Megatron-LM, JAX and more31; KubeRay Weights and checkpoints A model store, and loaders that stream weights into GPU memory as they arrive32 Storage sized for checkpoint bursts The pattern down the table: the pod is the wrong unit for both workloads. Each project adds a bigger one (a group, a gang, a set) that is scheduled, placed and restarted together, and teaches the scheduler a topology it otherwise can’t see. Most of it is young. Kubeflow Trainer still calls itself alpha,31 llm-d reached 1.0 only in October 2026,15 and Grove and LeaderWorkerSet overlap. Pin versions, and expect to swap a layer. What breaks? At scale, failure is the steady state. Over a 54-day snapshot of Llama 3 405B pre-training on 16,384 H100s, Meta logged 419 unexpected interruptions, about one every three hours. Some 78% were confirmed or suspected hardware, led by faulty GPUs (30.1%) and HBM3 memory (17.2%). Six were silent data corruption: wrong numbers, no error.16 That’s one failure per 50,000 GPU-hours or so. If failures scale with GPU count, a 1,024-GPU job meets one every two days. Recovery means restarting from a checkpoint, and the interval has a classic answer. With \(\delta\) the time to write a checkpoint and \(M\) the mean time between interrupts, Young’s first-order optimum, refined by Daly, is33 \[\tau \approx \sqrt{2 \delta M}\] and the fraction of the run lost is roughly \(\delta/\tau + \tau/(2M)\): writing checkpoints, plus redoing the work since the last one. At \(M = 185\) minutes, a five-minute checkpoint gives \(\tau \approx 43\) minutes and loses about 23% of the run. A 30-second one gives about 14 minutes and loses about 7%, before restarts. Write speed is the lever. Llama 3’s storage sustained 2 TB/s and peaked at 7 TB/s, because checkpoints arrive as bursts that saturate it, and Meta kept effective training time above 90%.16 The rest of the list, for serving: Round-robin throws away the cache. A plain load balancer scatters a conversation’s turns across replicas, and each one recomputes the prefix. Route on cache and load.29 Busy isn’t healthy. A GPU can report itself fully used while latency targets break. Scale on queue depth, cache use or the targets themselves, as Dynamo’s planner does.19 Cold starts are measured in weights. A replica isn’t ready until 70 GB, or several hundred, reach its GPUs. Pre-stage weights on nodes or stream them; in an air gap, from the model store inside it.32 A multi-host replica lives and dies whole. Lose one pod of a 16-GPU replica and the group restarts.23 Rolling updates need spare capacity in replica-sized units: 16 free GPUs to surge one replica. The network falls back quietly. Without RDMA devices and the IPC_LOCK capability in the pod, NCCL drops to TCP; check its logs for NET/IB/GDRDMA. The container’s default /dev/shm is too small, so mount a memory-backed volume.17 And for training: Gang or deadlock. Two jobs that each get half their pods hold the whole cluster and progress on neither. Admit all or nothing.2627 Placement is performance. A job scattered across racks puts its chattiest traffic on the slowest links. Schedule by topology.26 Kubernetes restarts pods; training restarts jobs. A replacement pod can’t rejoin a collective that has moved on, so recovery is the whole job, from the last checkpoint.25 Stragglers set the pace. One slow GPU, hot node or flaky link slows every step. Llama 3 saw throughput swing 1–2% with the time of day, as mid-day heat changed GPU clocks.16 Corruption doesn’t crash. It surfaces as a loss spike, or a worse model weeks later. A study of a large production fleet found hundreds of defective CPUs across hundreds of thousands of machines, and argued the problem is systemic;34 GPUs are no exception.16 Power moves with the job. Thousands of GPUs stalling and resuming together swing a data centre’s draw by tens of megawatts.16 An air gap compounds all of it. Driver, RDMA stack, NCCL and engine versions must match on every node, and each arrives through the one import path, so the cluster runs from a single tested bill of materials, upgraded as a whole. And for the CTO weighing this against an API? Owning the box pays when: the data can’t leave the building, by regulation or by choice usage is steady and high enough to keep batches full, where the per-token cost falls 100-fold an open model the size of the box does the job, judged on your own evaluation set Rent the API when usage is spiky, the best model matters more than control, or there’s nobody to run the platform. So, can you serve intelligence yourself? Yes: the hardware is affordable, the models are good, and the power bill is small. At cluster scale the hard parts are moving bytes across the slowest link and surviving failure, and Kubernetes now has a project for each. The ownership that pays off is of the platform around the boxes, built once and reused on every box and rack after it. Tom’s Hardware, “TinyBox AI accelerator now available starting at $15k, available in 7900XTX and RTX 4090 variants,” 2024; current models at https://docs.tinygrad.org/tinybox/. https://www.tomshardware.com/pc-components/gpus/tinybox-ai-accelerator-now-available-starting-at-dollar15k-available-in-7900xtx-and-rtx-4090-variants ↩ NVIDIA, “DGX Spark” product page and specifications (128 GB LPDDR5x unified memory, 273 GB/s, up to 1 PFLOP FP4 with sparsity, ConnectX-7 at 200 Gb/s, 240 W power supply, 200B-parameter inference and 70B-parameter fine-tuning claims). https://www.nvidia.com/en-us/products/workstations/dgx-spark/ ↩ ↩2 ↩3 The Register, “Nvidia’s GB10 Spark,” 13 October 2025 (launch price). NVIDIA later raised the US price, citing memory supply. https://theregister.com/2025/10/13/nvidia_gb10_spark ↩ NVIDIA, “H100 Tensor Core GPU” specifications (H100 SXM: 3.35 TB/s memory bandwidth). https://www.nvidia.com/en-us/data-center/h100/ ↩ ↩2 Jerry Zhou and Richard Chen, “NVIDIA DGX Spark In-Depth Review,” LMSYS, 13 October 2025. The authors note that results may become outdated as software support matures. https://www.lmsys.org/blog/2025-10-13-nvidia-dgx-spark ↩ ↩2 ↩3 OpenAI, gpt-oss-120b model card (116.8B total parameters, about 5.13B active per token; MoE weights in MXFP4 at 4.25 bits). https://huggingface.co/openai/gpt-oss-120b ↩ Tim Dettmers et al., “QLoRA: Efficient Finetuning of Quantized LLMs,” NeurIPS 2023; arXiv:2305.14314. https://arxiv.org/abs/2305.14314 ↩ ↩2 Collabnix, “Setting up a K3s Kubernetes cluster on NVIDIA DGX Spark with full GPU support” (community guide), and the NVIDIA Developer Forums thread “Blackwell GB10 GPU, device plugin v0.18.0, driver 580.95.05.” https://collabnix.com/setting-up-a-k3s-kubernetes-cluster-on-nvidia-dgx-spark-with-full-gpu-support/; https://forums.developer.nvidia.com/t/blackwell-gb10-gpu-device-plugin-v0-18-0-driver-580-95-05/348704 ↩ ↩2 Red Hat Developer, “Measure what matters: benchmarking and evaluation” (GuideLLM rate sweeps against OpenAI-compatible servers, with TTFT and ITL percentiles). https://developers.redhat.com/learning/learn:openshift-ai:get-started-vllm/resource/resources:measure-what-matters-benchmarking-and-evaluation ↩ NVIDIA Technical Blog, “Benchmarking LLM Inference at Scale with AIPerf.” https://developer.nvidia.com/blog/benchmarking-llm-inference-at-scale-with-aiperf ↩ NVIDIA Technical Blog, “LLM Benchmarking: Fundamental Concepts” (differences in metric definitions between tools). https://developer.nvidia.com/blog/llm-benchmarking-fundamental-concepts ↩ K3s documentation, “Air-Gap Install.” https://docs.k3s.io/installation/airgap ↩ RKE2 documentation, “Air-Gap Install.” https://docs.rke2.io/install/airgap ↩ NVIDIA GPU Operator 26.7, “Platform Support” (DGX Spark listed under Blackwell). https://docs.nvidia.com/datacenter/cloud-native/gpu-operator/26.7/platform-support.html ↩ llm-d, GitHub repository (v1.0, October 2026: inference scheduler, disaggregation, tiered KV cache on vLLM and SGLang). https://github.com/llm-d/llm-d ↩ ↩2 ↩3 ↩4 Aaron Grattafiori et al., “The Llama 3 Herd of Models,” arXiv:2407.21783, July 2024 (revised November 2024): §3.3.1 infrastructure and storage, §3.3.2 parallelism and MFU, §3.3.4 reliability, Table 3 architecture, Table 5 interruption causes. https://arxiv.org/abs/2407.21783 ↩ ↩2 ↩3 ↩4 ↩5 ↩6 ↩7 ↩8 ↩9 ↩10 vLLM documentation, “Parallelism and Scaling.” https://docs.vllm.ai/en/latest/serving/parallelism_scaling.html ↩ ↩2 ↩3 ↩4 Yinmin Zhong et al., “DistServe: Disaggregating Prefill and Decoding for Goodput-optimized Large Language Model Serving,” OSDI 2024; arXiv:2401.09670. https://arxiv.org/abs/2401.09670 ↩ NVIDIA Dynamo, GitHub repository (disaggregated serving, KV-aware routing, KV block manager, NIXL transfers, SLA-driven planner). https://github.com/ai-dynamo/dynamo ↩ ↩2 ↩3 Samyam Rajbhandari et al., “ZeRO: Memory Optimizations Toward Training Trillion Parameter Models,” arXiv:1910.02054, 2019 (§3.1: 2Ψ + 2Ψ + 12Ψ = 16Ψ bytes for mixed-precision Adam). https://arxiv.org/abs/1910.02054 ↩ ↩2 Deepak Narayanan et al., “Efficient Large-Scale Language Model Training on GPU Clusters Using Megatron-LM,” SC 2021; arXiv:2104.04473. https://arxiv.org/abs/2104.04473 ↩ ↩2 Kubernetes blog, “Kubernetes v1.34: DRA has graduated to GA,” 1 September 2025. https://kubernetes.io/blog/2025/09/01/kubernetes-v1-34-dra-updates/ ↩ Kubernetes SIGs, LeaderWorkerSet. https://github.com/kubernetes-sigs/lws ↩ ↩2 NVIDIA Dynamo documentation, “Grove” (PodCliqueSet, PodClique, PodCliqueScalingGroup; scheduling through KAI Scheduler). https://docs.nvidia.com/dynamo/knowledge-base/kubernetes/multinode/grove.md ↩ Kubernetes SIGs, JobSet (failure policy recreates the whole JobSet; exclusive placement per topology domain). https://github.com/kubernetes-sigs/jobset ↩ ↩2 Kueue documentation, “Topology Aware Scheduling”; Kueue v0.15.0 release announcement (TAS for Kubeflow Trainer v2). https://kueue.sigs.k8s.io/docs/concepts/topology_aware_scheduling/ ↩ ↩2 ↩3 NVIDIA, KAI Scheduler (CNCF sandbox; Apache-2.0). https://github.com/NVIDIA/KAI-Scheduler ↩ ↩2 SchedMD, Slinky slurm-operator. https://slinky.schedmd.com/projects/slurm-operator ↩ Kubernetes SIGs, Gateway API Inference Extension. https://gateway-api-inference-extension.sigs.k8s.io/ ↩ ↩2 KServe, “KServe 0.17 release,” March 2026 (LLMInferenceService on llm-d, disaggregated prefill and decode). https://kserve.github.io/website/blog/kserve-0.17-release ↩ Kubeflow Trainer, GitHub repository (v2.4.0, November 2026; status alpha). https://github.com/kubeflow/trainer ↩ ↩2 Run:ai Model Streamer, GitHub repository. https://github.com/run-ai/runai-model-streamer ↩ ↩2 J. T. Daly, “A higher order estimate of the optimum checkpoint interval for restart dumps,” Future Generation Computer Systems 22(3), 303–312, 2006 (extends J. W. Young’s first-order estimate). https://laro.lanl.gov/esploro/outputs/journalArticle/A-higher-order-estimate-of-the/9916364420003761 ↩ Harish Dattatraya Dixit et al., “Silent Data Corruptions at Scale,” arXiv:2102.11245, 2021. https://arxiv.org/abs/2102.11245 ↩ --- # The Architecture & Economics of AI Sovereignty URL: https://platformatory.io/blog/ai-sovereignty-intelligence-utility/ Published: 2026-11-02 Authors: Pavan Keshavamurthy Categories: AI, Platform Engineering, Infrastructure, Strategy There’s an old joke about a lecture on the cosmos, interrupted by someone insisting the world rests on the back of a giant turtle. What holds up the turtle? “It’s turtles all the way down.” The AI supply chain is turtles all the way down, and each turtle is a wrapper around the one beneath it: The AI product is a wrapper around a model API. The model is a wrapper around accelerators: trained and served on NVIDIA GPUs or Google TPUs, with its weights shaped by the hardware they ran on. The accelerator is a wrapper around a design and a fab. Design is the visible moat, years of architecture and software. Fabrication is the quieter one: a craft perfected by a few, with TSMC taking about 70% of global foundry revenue in Q2 2025.1 Its memory comes from three suppliers, SK hynix with about half.2 The fab is a wrapper around lithography: EUV scanners from one Dutch company, ASML, built around US light-source modules and German lasers.3 ASML is a wrapper around Carl Zeiss, its sole supplier of the mirrors and optics for EUV; Zeiss’s output caps ASML’s.4 Zeiss is a wrapper around precision machine tools and materials. Machine tools have been strategic for decades: in the 1980s, milling machines sold to the Soviet Union cut quieter submarine propellers, and members of Congress smashed a Toshiba radio on the Capitol lawn in protest.56 Under all of it: neon for lithography lasers, more than half of it from Ukraine until 2022,7 high-purity quartz for silicon crucibles, almost all of it from one North Carolina town that a hurricane shut for days in 2024,89 and power, about 415 TWh for data centres in 2024, heading for around 945 TWh by 2030.10 Where does it end? Nowhere convenient. More than 50 points in the semiconductor supply chain have a single region holding over 65% of the global market.11 In 1954 the US Atomic Energy Commission promised electricity “too cheap to meter.” Fuel was cheap; the plants and grid were not, and the meter stayed.12 In March 2026 the phrase came back with intelligence as “a utility, like electricity or water,” sold “on a meter.”13 If every hospital, court, ministry and company comes to need intelligence the way it needs electricity, the questions become a utility’s: who owns the plant, where it sits, and what happens in an outage. Utilities attract tariffs, stockpiles, guarded plants and the language of national security, and so governments everywhere now talk about sovereign AI. Over a stack of turtles, what would that even mean? Sovereignty arrives with analogies attached, and each one breaks somewhere. A standing army? Armies are sovereign capacity: force a state can use without asking permission. Yet most armies fly jets and run engines built abroad. Military sovereignty in practice means you can operate and maintain what you have, independently, and replace it through allies. Military technology? Governments already treat AI that way. The US controlled advanced AI chips and chipmaking tools in October 2022,14 and in January 2025 briefly wrote closed model weights into export law.15 Owning the goods? Full ownership means controlling every one of these: frontier and domain models with their training data; accelerator design and the software to design chips; leading-edge fabrication; high-bandwidth memory; EUV lithography; the optics inside it; specialty chemicals; gases and materials; power and cooling; precision machine tools. The chemicals show how fast a single layer can bite. In July 2019 Japan restricted exports of photoresist, hydrogen fluoride and fluorinated polyimide to South Korea, home of the world’s largest memory makers. Before the curbs, South Korea sourced 92% of its photoresist and 94% of its fluorinated polyimide from Japan.16 So is full sovereignty achievable? No country has it, the United States included: its AI runs on Dutch lithography, German optics, Taiwanese fabrication and Japanese chemicals. Autarky over the whole stack is a myth. The useful question is which layers to own, in what order. Maslow ordered human needs as a pyramid: physiological needs at the base, safety above them, then belonging, esteem and, at the top, self-actualisation. You don’t pursue the upper levels while the base is unmet. AI sovereignty has the same shape: Operational sovereignty (the base). Your AI keeps running if a foreign provider, or its government, says no: serving capacity on your soil, open weights you hold, people who can run and fix it. The bare minimum, and the one to secure first. Data sovereignty (safety). Your data stays under your law, in your languages. Model sovereignty (belonging). Domain and regional models, adapted and distilled for your industries and languages. Compute security (esteem). Accelerator supply secured through stockpiles, contracts and allies. Industrial sovereignty (self-actualisation). Fabs, lithography, optics, machine tools: the summit some aim for and nobody completes alone. Most sovereign-AI plans start at the summit (a national fab, a national chip) while the base stays unmet: a ministry whose chatbot stops if one API key is revoked. Public compute pools that rent subsidised GPUs to local startups and researchers start at the base instead. For policy, the pyramid sets the order of spending. Operational sovereignty is an architecture before it is a policy. Drawn as a system, it has six parts: A policy router at the front door: it classifies each request by sensitivity and residency, decides where the work may run, and holds the failover plan. A shared domestic serving pool: open-weight models and distilled domain and language models, on GPUs inside the border, run by people inside the border. A model registry holding the weights locally, versioned and escrowed, so a licence change abroad can’t take them away. An evaluation harness in local tasks and languages, the only way to know whether a domestic model is good enough for a court summary in Tamil or a claims form in Bahasa. A distillation pipeline that turns logged traces and graded examples into smaller students. A frontier API across the border: optional, for non-sensitive work, and mostly a teacher under contract. We build data platforms and agentic systems for customers, so we have a stake in how this gets built. The test is a drill: cut the border link for a week. Sensitive and essential work shouldn’t notice; frontier-only features degrade, visibly and on purpose. Run it before a supplier or a government runs it for you. What does intelligence cost at population scale? A utility sizes its grid from demand, and the same arithmetic works here. For \(U\) people at \(D\) tokens a day, a peak-to-average ratio \(f\), and a GPU serving \(r\) tokens per second at full batch, the fleet is \[N = \frac{f\, U D}{86\,400\; r}\] and the yearly cost per person, for a GPU-hour price \(h\) at average utilisation \(u\), is \[A = \frac{365\, D\, h}{3600\; r\, u}\] Four of the inputs are choices, and they vary by orders of magnitude: Demand \(D\): about 2,000 tokens a day for occasional chat, 20,000 for a daily assistant, 200,000 for agents that resend context at every step Model efficiency \(r\): illustratively 5,000 tokens per second per GPU for a small distilled model, 2,000 for a mid-sized open model, a few hundred for frontier-class models Utilisation \(u\): 0.5 for a fleet sized for twice its average load; higher only by pooling demand The hour \(h\): priced in dollars everywhere. H100 rental medians fell from $9.34 at hyperscalers in late 2024 to $1.95 on marketplaces by late 2025.17 Power is a small part of it: 700 W18 with a 1.3 facility overhead at $0.10 per kWh is $0.09 an hour, under 5% of $2. The hour is mostly capital. The fifth input is the one a country doesn’t choose: income per head \(y\). With \(h = \$2\) and \(u = 0.5\), set against the World Bank’s income bands:19 Workload and model Per person, per year Low income ($1,000) Lower-middle ($2,700) Upper-middle ($10,000) High ($60,000) Assistant, small distilled model $1.60 0.16% 0.06% 0.02% <0.01% Assistant, mid-sized open model $4.10 0.41% 0.15% 0.04% 0.01% Agents, mid-sized open model $41 4.1% 1.5% 0.41% 0.07% Agents, frontier-class model $270 27% 10% 2.7% 0.45% Illustrative throughput and demand. Measure \(r\) on your own models and hardware. So the economics reduce to one ratio: \[\frac{A}{y} = \frac{365\, D\, h}{3600\; r\, u\, y}\] \(h\) is set globally and \(y\) locally, and across economies \(y\) spans more than fifty-fold. Everything else is engineering. A high-income economy can afford frontier agents for everyone. A lower-middle-income one can afford an assistant for everyone and agents for some, on distilled models at high utilisation. For most of the world, sovereignty is won on \(r\) and \(u\): small models and pooled grids. Scale changes little of this. An assistant tier for 100 million people, about a twentieth of the 1.3 quadrillion tokens a month Google reported across its products in October 2025,20 needs about 23,000 GPUs and 21 MW,18 0.04% of what the world’s data centres used in 2024.10 DeepSeek-V3’s final training run took 2.788 million H800 GPU-hours, priced by its authors at $5.6 million;21 that fleet burns the same GPU-hours in about five days and seventy times as many in a year. Serving is the bill, and a pool at 75% utilisation pays a third as much per token as one at 25%. Pooled demand is what makes a utility cheap, which argues for shared national or sector pools over a cluster per ministry. Meanwhile the headline plans are priced at the summit: the EU’s InvestAI aims to mobilise €200 billion, including a €20 billion fund for AI gigafactories.22 How GPU-poor is each economy, relative to what its people already use? Two public datasets give a rough answer: Epoch AI’s census of GPU clusters, in H100-equivalents,23 and Microsoft’s share of working-age adults using AI at the end of 2025,24 applied to World Bank working-age populations.25 The model above gives the yardstick: an assistant tier at 20,000 tokens a day needs about 231 H100-class GPUs per million users. Economy AI users (millions) Tracked H100-equivalents Per million AI users Against the assistant-tier need United States 62.3 940,850 15,100 65× Finland 0.9 11,846 12,560 54× Norway 1.7 20,480 12,180 53× Germany 15.0 26,050 1,730 7.5× Japan 13.9 18,156 1,300 5.6× Saudi Arabia 6.8 8,391 1,240 5.4× France 18.5 16,119 870 3.8× China 159.2 109,411 690 3.0× South Korea 11.1 6,286 560 2.4× United Kingdom 17.1 7,972 470 2.0× Singapore 2.7 1,135 410 1.8× Canada 9.4 3,109 330 1.4× United Arab Emirates 5.8 1,749 300 1.3× Brazil 25.1 1,215 50 0.2× India 155.4 4,303 30 0.1× Indonesia, Mexico, Pakistan, Philippines, Nigeria 12 to 25 each none tracked 0 0 Tracked clusters only, as of mid-2025.23 The caveats are large: Coverage: the census captures an estimated 10–20% of global GPU cluster performance, Chinese entries are anonymised and rounded, and most hyperscaler cloud regions and many national programmes are missing.23 Location versus use: Finland and Norway rank high on shared European supercomputers; American clusters serve the world. A GPU in another country is capacity you rent, which is the dependency this essay is about. Demand moves: AI adoption grew in every economy on Microsoft’s list through 2025.24 Even so, the shape is clear. A handful of economies hold many times their own assistant-tier demand. China and most of Europe hold a few times theirs. The largest pools of users, in India, Brazil, Indonesia, Mexico, Pakistan, the Philippines and Nigeria, hold a fraction of theirs or none on record, and rent the rest across a border. How does an AI grid make money? The same way any grid does: sell capacity and meter usage, and recover capital before the asset ages out. Capacity: reserved GPUs under long contracts, ideally with an anchor tenant such as a government or a telco Metered tokens: wholesale to applications and distributors, priced per million Services above the meter: fine-tuning, evaluation, compliant hosting for regulated data The risk is the price of the hour. A grid financed at 2024’s rental prices and rented at 2025’s loses money on every hour,17 and each hardware generation resets the curve. Grids that last will look like utilities: long contracts, high utilisation, regulated or anchor-backed returns. The middle of the stack is a thin-margin business. Who makes the money, then? The turtles below: NVIDIA’s data-centre revenue reached $193.7 billion in fiscal 2026, at a 71.1% company gross margin.26 Much of every GPU-hour repays that margin, and in most countries it leaves the country. Whoever owns the customer: telcos and app platforms that put intelligence on a bill people already pay. Owners of domain models: data, evaluations and distribution in a vertical or a language are harder to copy than a GPU cluster. Grid operators: utility returns at best, losses when the hour reprices. The economy at large: most of the value lands as productivity in the work that uses the tokens, and none of it appears on the grid’s income statement. India has more AI users than any economy except China, on a GDP per head of $2,702 in 2025,27 in the World Bank’s lower-middle-income band.19 GPU poverty: the census above tracks about 4,300 H100-equivalents in India. Counting the national programme’s 38,000-plus GPUs28 lifts that to about 270 per million AI users, if the two don’t overlap: roughly the assistant tier for today’s users, a sixth of it if every working-age adult took it up, and a tenth of an agent tier Users: ChatGPT’s daily active users in India reached 73 million in late 2025, more than double the US figure;29 Reliance Jio alone has about 500 million customers.29 The hour: the national programme’s common compute facility rents 38,000-plus GPUs at an average of about ₹65 per GPU-hour.28 The bill people already pay: Jio’s average revenue per user (ARPU) was ₹213.7 a month in the December 2025 quarter.30 An assistant for 500 million people, at 20,000 tokens a day on a mid-sized open model (\(r = 2{,}000\), \(u = 0.5\), \(h = \text{₹}65\)): Fleet: about 116,000 GPUs, three times what the programme has onboarded Power: about 106 MW, under 1 TWh a year Cost: about ₹6,600 crore a year: ₹132 per person, or ₹11 a month, about 5% of that ARPU At twice the GPU-hour price: ₹22 a month Agents for 50 million people at 200,000 tokens a day need another 116,000 GPUs and cost about ₹110 a month each on a mid-sized open model, half the ARPU. On a frontier-class model the same agents cost about ₹730 a month, 3.4 times what the average customer pays for their phone. So in India intelligence is affordable for everyone as an assistant on domestic, distilled models, and affordable as agents only for the top tier or on small models. The market is already pricing it that way. Late 2025 brought ChatGPT Go free for a year, Google’s AI Pro free for 18 months to Jio’s customers, and Perplexity Pro free for a year to Airtel’s. Analysts read the offers as a hunt for users and for training data in India’s languages.29 Intelligence is being sold the way mobile data was: bundled into a telco bill and priced in rupees per month. Who makes money in India on this path? The telcos, which own the bill; foreign model owners, which collect the users and the data; and chip vendors abroad, which are paid for every imported GPU. Operational sovereignty keeps the ₹11 a month at home: a domestic grid running Indic, domain-distilled models at high utilisation, with the frontier as the teacher. And operational sovereignty runs straight back to models. You can’t keep AI running on your own soil without models you hold: for your domains (law, health, finance, agriculture), your regions and your languages. You will still want frontier models, but as machine tools. The frontier model is also a machine tool, the machine that makes the machines. Its most consequential output is other models: synthetic training data, labelled edge cases, graded outputs, and the teacher that smaller students are distilled from. Distillation dates to 2015, when a small model trained to imitate a large one was shown to keep much of its skill at a fraction of the size.31 It’s now routine: DeepSeek shipped R1 in January 2025 together with smaller dense models distilled from its reasoning traces.32 The big model’s job is to make the small ones good. Machine tools end up controlled, and so do these. The January 2025 rule on model weights was rescinded four months later,33 but the category survives the rule. My prediction: frontier weights end up near enriched uranium, licensed, audited, rented through metered APIs with know-your-customer checks, and kept off the open market. A handful of labs, each close to a government, will run the generating plants. The serious objection is open weights. R1 shipped with its weights, and if the open frontier stays within months of the closed one there’s nothing to guard. The number to watch is the lag between the best closed and best open model on agent tasks. If it holds near zero, I’m wrong. If it holds at a year while export rules tighten, the plants stay behind the fence. Either way, the base of the pyramid is the same: models you hold, built or distilled for your domains, regions and languages, with the frontier as the machine tool that makes them. Most organisations need no power station of their own. They need to know what to run on the meter, and how little of it they can get away with. Nations guard the machines that make machines. Rent the generator; own what it powers. A utility is a supplier, and suppliers have outages. TrendForce figures for Q2 2025 foundry revenue (TSMC 70.2%), as reported by Notebookcheck. https://www.notebookcheck.net/Global-foundry-revenue-surged-to-41-7-billion-in-q2-2025-with-TSMC-capturing-a-record-70-percent-market-share.1102353.0.html ↩ TrendForce, “HBM market heats up as three giants clash with HBM4 at the center,” 17 September 2025 (SK hynix projected at 52.3% of 2025 HBM share). https://www.trendforce.com/news/2025/09/17/news-hbm-market-heats-up-as-three-giants-clash-with-hbm4-at-the-center/ ↩ ASML, “Making EUV: from lab to fab,” 2022. https://www.asml.com/en/company/stories/2022/making-euv-lab-to-fab ↩ Tom’s Hardware, “Zeiss expands German site that caps ASML’s EUV scanner output,” citing ASML’s 2025 annual report (Carl Zeiss SMT is ASML’s sole supplier of critical optical components). https://www.tomshardware.com/tech-industry/zeiss-expands-german-site-that-caps-asmls-euv-scanner-output ↩ King’s College London, “The Toshiba-Kongsberg case,” 22 September 2014. https://www.kcl.ac.uk/news/the-toshiba-kongsberg-case ↩ United Press International, “Lawmakers hammer Toshiba,” 1 July 1987. https://www.upi.com/Archives/1987/07/01/Lawmakers-hammer-Toshiba/3984552110400/ ↩ CNBC, “Chip industry under threat with neon production set to fall off a cliff following Russia’s invasion of Ukraine,” 25 March 2022 (Ingas and Cryoin halted, per Reuters; Ukraine’s share per Bain & Co.). https://www.cnbc.com/2022/03/25/russia-ukraine-war-laser-neon-shortage-threatens-semiconductor-industry.html ↩ Megan Cassella, “How a tiny town hit by Helene could upend the global semiconductor chip industry,” CNBC, 3 October 2024 (republished by NBC New York). https://www.nbcnewyork.com/news/business/money-report/how-a-tiny-town-hit-by-helene-could-upend-the-global-semiconductor-chip-industry/5855037/ ↩ Bloomberg via BNN Bloomberg, “North Carolina Quartz Mine Owner Says Helene Damage Was Minimal,” 4 October 2024. https://bnnbloomberg.ca/investing/2024/10/04/north-carolina-quartz-mine-owner-says-helene-damage-was-minimal ↩ International Energy Agency, Energy and AI, executive summary, 2025 (data centres used about 415 TWh in 2024, around 1.5% of global electricity; base case of about 945 TWh by 2030). https://www.iea.org/reports/energy-and-ai/executive-summary ↩ ↩2 Semiconductor Industry Association and BCG, “Strengthening the Global Semiconductor Supply Chain in an Uncertain Era,” April 2021. https://www.semiconductors.org/wp-content/uploads/2021/03/SIA-BCG_Global-Value-Chain_2-pager.pdf ↩ US Nuclear Regulatory Commission, “Too Cheap to Meter: A History of the Phrase” (Strauss’s address to the National Association of Science Writers, 16 September 1954, and the industry reaction). https://www.nrc.gov/reading-rm/basic-ref/students/history-101/too-cheap-to-meter.html ↩ Business Insider via AOL, “Sam Altman says AI will eventually be sold like electricity and water — by companies like OpenAI,” March 2026 (BlackRock U.S. Infrastructure Summit, 11 March 2026). https://www.aol.com/news/sam-altman-says-ai-eventually-152157395.html ↩ US Bureau of Industry and Security, “Commerce Implements New Export Controls on Advanced Computing and Semiconductor Manufacturing Items to the People’s Republic of China,” 7 October 2022. https://www.bis.gov/press-release/commerce-implements-new-export-controls-advanced-computing-semiconductor-manufacturing-items-peoples ↩ Gibson Dunn, “BIS Lays the Groundwork for Global and Metered Access to Frontier AI Models and the Computing Power to Train Them,” January 2025, on the interim final rule of 13 January 2025 (ECCN 4E091, closed-weight models trained with more than 10²⁶ operations). https://gibsondunn.com/bis-lays-groundwork-for-global-and-metered-access-to-frontier-ai-models-and-computing-power-to-train-them ↩ Japan Today, “Factbox: The high-tech materials at the heart of a Japan-S.Korea row,” 2019 (import shares from Korea Trade Association data). https://japantoday.com/category/business/factbox-the-high-tech-materials-at-the-heart-of-a-japan-s.korea-row ↩ Silicon Data, “H100 rental price over time,” H100 Rental Price Index (hyperscaler median $9.34 per GPU-hour, June to December 2024; July to December 2025: hyperscaler $6.26, neocloud $3.33, marketplace $1.95). https://www.silicondata.com/blog/h100-rental-price-over-time ↩ ↩2 NVIDIA, “H100 Tensor Core GPU” specifications (H100 SXM: up to 700 W, configurable). https://www.nvidia.com/en-us/data-center/h100/ ↩ ↩2 World Bank, “World Bank Country and Lending Groups,” fiscal year 2027 (2025 GNI per capita, Atlas method: low income $1,175 or less; lower-middle $1,176 to $4,635; upper-middle $4,636 to $14,375; high above $14,375; India lower-middle). https://datahelpdesk.worldbank.org/knowledgebase/articles/906519-world-bank-country-and-lending-groups ↩ ↩2 Sundar Pichai, “Q3 earnings call: Remarks from our CEO,” Google, 29 October 2025 (“over 1.3 quadrillion monthly tokens,” up from 980 trillion announced in July). https://blog.google/inside-google/message-ceo/alphabet-earnings-q3-2025/ ↩ DeepSeek-AI, “DeepSeek-V3 Technical Report,” arXiv:2412.19437, December 2024 (2.788M H800 GPU-hours for the official training run at an assumed $2 per GPU-hour; prior research and ablation experiments excluded). https://arxiv.org/abs/2412.19437 ↩ European Commission, “EU launches InvestAI initiative to mobilise €200 billion of investment in artificial intelligence,” 11 February 2025. https://digital-strategy.ec.europa.eu/en/news/eu-launches-investai-initiative-mobilise-eu200-billion-investment-artificial-intelligence ↩ Epoch AI, “Data on GPU clusters” (formerly “AI Supercomputers”), CC BY, accessed November 2026 (H100-equivalents summed by country over existing, non-superseded clusters; the dataset covers an estimated 10–20% of global GPU cluster performance as of March 2025; Chinese systems anonymised and rounded). https://epoch.ai/data/gpu-clusters ↩ ↩2 ↩3 Microsoft AI Economy Institute, AI Diffusion Report 2025 H2, January 2026 (AI user share of the working-age population by economy, H1 and H2 2025). https://www.microsoft.com/en-us/research/wp-content/uploads/2026/01/Microsoft-AI-Diffusion-Report-2025-H2.pdf ↩ ↩2 World Bank, World Development Indicators, “Population ages 15-64, total” (SP.POP.1564.TO), 2024. https://data.worldbank.org/indicator/SP.POP.1564.TO ↩ NVIDIA, “NVIDIA Announces Financial Results for Fourth Quarter and Fiscal 2026,” 25 February 2026 (data-centre revenue $193.7 billion; GAAP gross margin 71.1%). https://investor.nvidia.com/news/press-release-details/2026/NVIDIA-Announces-Financial-Results-for-Fourth-Quarter-and-Fiscal-2026/default.aspx ↩ World Bank data via FRED, “Gross Domestic Product Per Capita for India” (PCAGDPINA646NWDB), 2025: $2,702.48. https://fred.stlouisfed.org/series/PCAGDPINA646NWDB ↩ Press Information Bureau, Government of India, IndiaAI Mission factsheet, February 2026 (38,000-plus GPUs available at ₹65 per hour). https://static.pib.gov.in/WriteReadData/specificdocs/documents/2026/feb/doc2026217795001.pdf ↩ ↩2 Reuters, “With freebies, OpenAI, Google vie for Indian users and training data,” 18 December 2025, as republished by Deccan Chronicle (ChatGPT daily active users in India up 607% to 73 million per Sensor Tower; offers from OpenAI, Google with Reliance Jio, and Perplexity with Airtel). https://www.deccanchronicle.com/technology/with-freebies-openai-google-vie-for-indian-users-and-training-data-1924649 ↩ ↩2 ↩3 TelecomTalk, “Jio Posts 3Q FY26 ARPU of Rs 213.7, Subscriber Base Crosses 515 Million.” https://telecomtalk.info/reliance-jio-posts-3qfy26-arpu-of-rs213/1003600/ ↩ Geoffrey Hinton, Oriol Vinyals and Jeff Dean, “Distilling the Knowledge in a Neural Network,” arXiv:1503.02531, 2015. https://arxiv.org/abs/1503.02531 ↩ DeepSeek-AI, “DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning,” arXiv:2501.12948, 22 January 2025. https://arxiv.org/abs/2501.12948 ↩ Kirkland & Ellis, “BIS Rescission of the Biden Administration’s AI Diffusion Rule,” May 2025 (rescission announced 13 May 2025). https://www.kirkland.com/publications/kirkland-alert/2025/05/bis-rescission-of-the-biden-administration ↩ --- # Programming in the Age of AI Slop URL: https://platformatory.io/blog/ai-slop-coding-productivity/ Published: 2026-11-01 Authors: Pavan Keshavamurthy Categories: AI, Software Engineering, Platform Engineering Since 2023 we have gone through a new meme every year or so about what these machines are. 2023, the parrot: fancy autocomplete, stitching together the form of language without its meaning. The best model resolved 1.96% of real GitHub issues on SWE-bench.1 The job of the future was prompt engineer, and one posting paid up to $335,000.2 2025, the vibes: “a new kind of coding I call ‘vibe coding’,” where you “forget that the code even exists.”3 In March, Anthropic’s CEO expected AI to be writing 90% of the code within three to six months.4 The sceptics had their own refrain: it’s slop. 2026, the factory: agents running for hours with nobody watching, sixteen of them building a C compiler, leaderboards ranking engineers by tokens burned, and machine-checked proofs offered for Millennium Prize problems. Each meme was half right, and each aged faster than the last. I started programming in my teens. I was good at Scrabble, borderline at chess, and hopeless at Yahoo Pool, with its five-second timed shots and somewhat questionable physics. So I did what any budding script kiddie would: I hacked the Java applet to build an auto-aimer. Result: I won every game. Then the long road. Lots of web development; learning C, then C++, like a real programmer; lots of competitive programming; a pile of open-source projects. They say that as you get older you think more about infrastructure, and databases. I’ll save that for another day. Was it all worth it, to end up typing to Claude: “Do X, step by step. Make no mistakes”? The auto-aimer is now the whole profession’s default. The line is drawn for you, and nobody has to learn to aim. Peter Naur described what’s at stake in 1985. Programming is “the programmers’ building up knowledge of a certain kind”: a theory of how the problem maps onto the code, which lives in people’s heads and “could not conceivably be expressed” in full. A program dies “when the programmer team possessing its theory is dissolved.” It keeps running; nobody can change it intelligently.5 So who holds the theory of a program no human wrote? Slop was 2025’s word of the year: “digital content of low quality that is produced usually in quantity by means of artificial intelligence.”6 The definition is economic. Slop is cheap, plentiful, and someone else’s job to clean up. Writing hurts more than the code. It’s the other craft I cultivated, making a story land, and it’s disrupted the same way. This essay was drafted with an AI from my notes, then argued with, cut and rewritten. The machine is a good researcher and a tireless first draft. It has nothing to say; that part was mine, and it’s the only part worth reading. Will children growing up now feel what I felt at fourteen, making a machine do something it wasn’t meant to, or finding the sentence that says exactly what I meant? The early evidence is thin: Study: 54 participants writing essays over several months, with ChatGPT, a search engine or nothing (MIT Media Lab preprint, 2025) Unaided writers: the strongest, most widely distributed brain connectivity ChatGPT writers: the weakest, and trouble quoting essays they had just written Caveats: small sample, tight time limits, a preprint7 It matches what anyone who learned a craft knows: the struggle is the skill, laid down in layers. Kids will still learn to aim, the way people still learn chess decades after engines beat the best humans: as a sport and an art. A craft survives as a hobby long after it stops being a trade. Then the machines got good. Until late 2025 a coding agent was an eager intern: fast, confident and in need of a minder. Claude Opus 4.5, in November 2025, was the turn. It “runs longer, does more, and requires less intervention,” and inside the two-hour limit of Anthropic’s performance-engineering take-home it scored higher than any human candidate ever had.8 Within three months agents were building systems: February 2026: 16 parallel Opus 4.6 agents, nearly 2,000 sessions over two weeks, just under $20,000. The result was a clean-room, 100,000-line C compiler in Rust that builds Linux 6.9 on x86, ARM and RISC-V, plus Postgres, SQLite and Doom, written without active human intervention.9 Task length at 50% success: about 4.9 hours for Opus 4.5, about 12 hours for Opus 4.6, about 17 hours for an early snapshot of Anthropic’s Mythos Preview in April 2026. METR treats anything above 16 hours as unreliable on its suite.10 Task length at 80% success: 49 minutes, 70 minutes, about 3 hours.10 My conclusion: software engineering for today’s requirements is definitively solved. Agents don’t need babysitting. They still need checking, and the gap between those two horizons is the work that’s left. The compiler’s author spent most of his effort “designing the environment around Claude”: the tests, the harness, the feedback.9 Its limits are the kind you find by measuring: it borrows GCC to boot 16-bit x86, has no assembler or linker of its own, emits slow code, and its Rust is “nowhere near” expert quality. Code was never the hardest part. A word to the angry artisans, and I was one not long ago. The complaint goes like this: programming was an art, and the shippers of slop have lost it. The daily evidence is real. A 180-file, 40,000-line pull request lands in your review queue, and it happens a lot. Reading it line by line is drudgery, and it catches less than it costs. My advice: that isn’t the way to go, and anything this puritanical is no longer worth preserving. Programming is following the path of everything that became computable. Computer was once a job title. At Langley, from 1935, rooms of women with mathematics degrees worked the numbers by hand, graded from Junior Computer to Chief Computer, until the machines took the arithmetic; some of them went on to become engineers and programmers of those machines.11 Brevity in code was a virtue while people wrote and read every line. It no longer seems worth the effort, unless poetry defines you, and code golf will survive as a sport, like chess. The new way, in four moves: Adversarial review: a second agent, told to break the change, reviews it before any human does, and the human reads the disagreements. Better evals: the 40,000-line pull request is judged against a golden set of real cases, and the diff is the last thing you read. Architecture as a constitution: the rules the code must obey (layering, dependencies, data ownership, what may touch money) written down, enforced in the build and handed to every agent. The factory as a platform: agentic AI run as an enterprise platform, with the line built around the agents. Production has split into two shapes. The software factory is an old idea. Hitachi pioneered the factory model for large-scale software in the late 1960s, chasing process, reuse and quality control at industrial scale.12 The 2026 version is the dark factory, named after lights-out plants: the top of a five-level ladder of AI-assisted coding, with rules like “Code must not be written by humans. Code must not be reviewed by humans.” Humans write goals, scenarios and hidden acceptance tests; the factory runs.13 Throughput is the product, and code is an intermediate good, like sawdust. The tokenmaxxing artisan is one engineer running a dozen agents, with token spend worn as a badge; some companies now score employees on it.14 The leverage is real, at a price. Q1 2026, 12,000 developers at 200 companies:15 Lowest-spending fifth: about $3 of tokens for the quarter, 11 merged PRs Highest-spending fifth: $1,822, 23 merged PRs Marginal cost: \(\frac{\$1{,}822 - \$3}{23 - 11} \approx \$150\) per extra merged PR, less than an hour of a senior engineer A merged PR measures activity, and both shapes share a blind spot. The factory swaps the person who holds Naur’s theory for a test suite. The artisan keeps that person and buries them in more code than one person can hold. Either way the theory thins out, and by Naur’s definition the program is born dead. Is the gain real? The most careful evidence on delivery: METR, 2025: randomised trial, 16 experienced open-source developers, 246 tasks in repositories they knew. AI made them 19% slower; they had expected 24% faster, and afterwards believed they had been 20% faster.16 METR, late 2025 follow-up: 57 developers, a speedup estimate with confidence intervals spanning zero, “only very weak evidence.” The study is being redesigned, partly because developers now refuse to work without AI.17 DORA 2025 (about 5,000 respondents): higher AI adoption now tracks higher throughput, and higher delivery instability.18 Faros (22,000 developers, two years): tasks completed up 34%, bugs per developer up 54%.19 The agents have improved enormously since those trials; the delivery evidence hasn’t caught up. The theory of constraints explains why: a system’s throughput is set by its bottleneck, and speeding up any other step piles inventory in front of it.20 Amdahl’s law gives the overall speedup \(S\) when a step taking share \(p\) of lead time gets \(k\) times faster: \[S = \frac{1}{(1 - p) + p/k}\] If writing code is 30% of lead time (\(p = 0.3\); illustrative, measure your own): 10× faster coding: \(S = 1/(0.7 + 0.03) \approx 1.37\times\) faster delivery Infinitely fast coding: \(S \to 1/0.7 \approx 1.43\times\) Illustrative: coding at 30% of lead time. The inventory piles up in the review queue, and the cost of a change is more than its tokens: \[C_{\text{change}} = C_{\text{tokens}} + t_{\text{review}}\, w + P_{\text{defect}}\, C_{\text{defect}} + P_{\text{vuln}}\, C_{\text{breach}} + C_{\text{slop}}\] where \(t_{\text{review}}\) is review time, \(w\) the engineer’s rate, and \(C_{\text{slop}}\) the cost pushed onto someone else. Tokens are the cheap term. The rest: Review. Code nobody holds a theory of is slower to review than a colleague’s. Defects. 54% more bugs per developer grows the defect term with throughput. Vulnerabilities. Across 100+ models and 80 tasks built around common weaknesses, generated code introduced a security flaw in 45% of cases, above 70% in Java.21 Invented dependencies. Of 2.23 million generated package references, 19.7% named packages that don’t exist: 205,000+ unique names, each free for an attacker to register. The attack is called slopsquatting.22 Externalised slop. curl ended its bug bounty in January 2026, after AI-generated reports pushed valid submissions below 5%; its maintainers had been paying for other people’s slop with their evenings.23 Net: real at the keyboard, smaller at the pull request, and close to zero for teams that don’t price in review, defects and security. The business moves at the speed of everything outside the editor: deciding what to build, approvals, legal review, procurement, the customer who has to change how they work. AI speeds up the cheapest link; the chain sets the pace. So the engineer becomes the verifier: the person who measures, evals and makes sure the code did what it was supposed to do. Reading every line doesn’t scale to a fleet of agents. Demonstrations do, each one measured: Behaviour: evals on a golden set of real cases, run on every change Types and contracts: type checkers, schemas, constrained output Architecture: dependency and layering rules enforced in the build Performance: benchmarks and load tests as gates, with budgets Security: scans, pinned and allowlisted dependencies, a threat model for anything that touches money or identity Correctness: specs, and proofs where they pay Security is where verification is least optional, because it is an economic property: how much would breaking this cost, and who would pay it? Scarcity used to protect most software. Skilled attackers were expensive, slow and few. Not any more: XBOW, 2025: an autonomous pentester, 1,000+ vulnerability reports in a few months, top of HackerOne’s US leaderboard.24 DARPA AI Cyber Challenge, August 2025: autonomous systems found 54 of 63 planted vulnerabilities, patched 43, and found 18 real ones nobody planted.25 GTG-1002, November 2025: an espionage campaign assessed as Chinese state-sponsored used an AI coding agent as an intrusion engine against about thirty targets, with AI doing an estimated 80–90% of the work.26 The same capability defends. The asymmetry stays: defenders must be right everywhere, and the attacker’s cost per attempt has fallen by orders of magnitude. Code generated quickly, verified thinly and full of plausible dependencies is cheap to break. Then sign-off. Uber’s former chief security officer was convicted in 2022 over the handling of its 2016 breach, believed to be the first criminal prosecution of an executive over a data breach.27 Regulators, courts and boards look for a person with a name. A slide attributed to a 1979 IBM training session put it in sixteen words: “A computer can never be held accountable. Therefore a computer must never make a management decision.”28 Every autonomous pipeline ends at a human signature, and that human owns the outcome, whoever did the execution. For engineering leaders, the moves: measure lead time and review-queue age, and stop counting PRs or tokens budget verification time explicitly as AI output grows pin and allowlist dependencies, and scan every generated change require a named human sign-off on anything touching money, identity or production The cost of the strongest demonstration, a proof, is collapsing: AWS, since 2011: TLA+ on critical systems, catching design bugs no other technique found.29 December 2025 prediction: AI will “totally change the economics of formal verification.” If a model writes the proof, you trust the checker instead of reading the code, and the work shifts to “correctly defining the specification.”30 2025 benchmark, 12,000+ formal specifications: off-the-shelf models produced verified programs for about 82% of Dafny tasks, 44% in Verus and 27% in Lean.31 Mathematics went first, because there the checker already existed. Lean checks a proof line by line, so a machine’s proof can be trusted without trusting the machine: January 2026: GPT-5.2 Pro and Harmonic’s Aristotle, operated by Kevin Barreto, resolved Erdős problem #728 with a formal proof in Lean, the first Erdős problem regarded as resolved autonomously by AI.32 May 2026: a formal proof-search agent autonomously resolved 9 of 353 open Erdős problems.33 September 2026: OpenAI claimed a resolution of the Navier–Stokes Millennium Prize problem, a finite-time singularity from smooth initial data, found by about 10,000 concurrent agents in 88 hours and formalised in Lean. Mathematicians are still checking it, and the Clay Institute rules only after peer review and a two-year wait.34 November 2026: Terence Tao reported Lean-formalised proofs of finite-time blowup for the unforced Euler and Navier–Stokes equations by Levent Alpöge and colleagues, with heavy AI assistance.35 A day later the Lean and Mathlib communities certified a proof of the Riemann Hypothesis by Alpöge, generated with an internal AI model:35 a Lean library of 17 million lines.36 The people in those stories chose the problem, built the setup and checked the result. That points to a meta-language for the rest of us. Spec-driven development is its first draft: tools that have the agent write requirements, a design and a task list before any code, and hold it to them.37 Push it further and the roles move with it: Product managers writing acceptance criteria as conjectures, statements precise enough for a machine to try to prove or refute Verification engineers writing torture suites in the style of GCC’s, the suite the agents’ C compiler had to pass9 Platform teams throwing deterministic simulation and fuzzing at all their infrastructure; FoundationDB was built inside a simulator from the start, and ran the equivalent of a trillion CPU-hours of simulated stress tests38 The first is speculative. The other two are how the most reliable systems were already built. Larry Page made a prediction at the American Association for the Advancement of Science in 2007: when AI happens, “it’s going to be a lot of computation, and not so much clever blackboard, whiteboard kind of stuff.”39 He was right, and you can see it in the output. What computation finds tends to be exhaustive: it covers every case where a person would have spotted the shortcut. Writing: a lack of brevity is the typical AI smell; the extra clause, the recap, three examples where one would do. Code: way more verbose than the best programmers write it. Mathematics, ironically, the purest form: the Riemann Hypothesis proof is 17 million lines of Lean, and digesting it will “take some time.”35 Do we really learn much from AI? Machines checked those 17 million lines within a day of their release. The Lean community’s own announcement ends by looking forward to mathematicians explaining the new ideas in them.36 The prices around the oldest gap in computer science, between finding an answer and checking one (P versus NP, which AI hasn’t settled), now look like this: Finding: cheap, bought with computation. Checking: cheap wherever a checker exists: Lean for proofs, tests and evals for code. Understanding: still human, and still expensive. That reconciles brevity with my advice to the artisans. Verbose code is a fair price where a machine checks it and nobody has to read it. Where a person has to understand the result (a post, a proof, the theory of a program) verbosity is a cost, and somebody has to pay it down. AI raises the bar twice: for what customers expect, and for the engineers who deliver it. The fashionable obituary says software is dead: models write the code and the profession deflates. Jevons saw the opposite with coal in 1865: more efficient engines made coal worth burning for more things, and consumption rose.40 Cheaper code does the same to software, and customer service shows the two ways to spend it. Klarna, February 2024: its AI assistant handled two-thirds of customer-service chats in its first month, the work of 700 full-time agents by its own count.41 By May 2025 the focus was back on the quality of human support.42 Air Canada, February 2024: ordered to honour a bereavement-fare policy its chatbot invented, after arguing it wasn’t liable for what the chatbot said. Damages: $812.02.43 The other way: the agent spots the delayed shipment before the customer does, rebooks the connection when the inbound flight slips, and files the claim with documents attached. Everyone gets the platinum tier, which takes more software and harder software: real integrations, idempotent writes, audit trails, a designed hand-off to a person. If an AI plan’s headline metric is something you remove (headcount, handle time, tickets reaching a human), you’re competing on price with everyone who bought the same model. If it’s something nobody could afford to offer last year, you have a product. The engineer’s bar rises with it. Verifying an agent’s work takes the judgment that used to come from years of writing the code yourself, and the entry rungs are thinning: workers aged 22 to 25 in the most AI-exposed occupations saw a 16% relative decline in employment from late 2022, after controlling for firm-level shocks, with software developers among the hardest hit.44 Experience is now the expensive input, and the industry will have to find new ways to grow it. The next round of work is domain work, and it will be eval-driven. “Stochastic parrots” (2021): systems that stitch together linguistic form without reference to meaning.45 Half right, and the half that matters is that fluency is no evidence of correctness. A million monkeys at a million typewriters would eventually produce Hamlet; give one monkey a crossword, where every crossing is a check, and the odds change. Levelling up an industry means drawing its crosswords: the evals that say what correct means in claims handling, freight, lending or care. The roles are already on job boards: Forward-deployed engineers: embedded with a customer, building the integrations and workflows that put a model into production. Monthly listings grew more than 800% from January to September 2025.46 Expert trainers: professionals paid to write, grade and critique model outputs in their own field. Mercor, one marketplace, says it hired 30,000 contractors in 2025, from finance analysts to linguists, and pays out about $2 million a day.47 Environment builders: engineers who build simulated workspaces where agents practise multistep tasks and are rewarded for finishing them; labs buy them from a new crop of startups.48 Eval writers: domain experts who label a golden set of real cases and run it on every prompt change and model upgrade, the unit tests for judgment. Harness designers: narrow verbs like issue_refund(order_id, amount) with the cap enforced in code, and crossings: schemas, rule engines, a second model, reconciliation against the system of record. Operators who still fly: on Air France 447 in 2009, the autopilot disconnected when ice blocked the airspeed probes and handed a sound aircraft to a crew that never recognised the stall.49 Agents will take diagnosis and most remediation; someone who has flown recently holds the pager. Most of these are software engineering applied to X, and most of the job is X. Frameworks turn over every eighteen months; a domain lasts a career. The engineer who thrives there is T-shaped with a broader bar: one deep stroke, and a bar wide enough to reach architecture, security, performance and the business. A polymath helps; breadth and taste are the requirement. AI supplies some of the breadth itself. In a field experiment with 776 Procter & Gamble professionals, R&D and commercial staff using AI produced proposals balancing technical and commercial elements whatever their background, and individuals with AI matched two-person teams without it.50 What stays scarce is taste: knowing which domains should meet, and noticing when the combination is wrong. Those engineers will run an increasingly bespoke software world. When building is cheap, the thin layer of SaaS turns out brittle: the workflow tool, the admin panel, the dashboard, the CRM nobody loved. In one 2026 survey of 817 builders, 35% had already replaced at least one SaaS tool with a custom build, mostly workflow automations, internal admin tools, BI and CRMs.51 The software stocks felt it in February 2026, and partly recovered by May. What holds is software that is very cheap, wins on scale, provides real security, or is the system of record. The infrastructure primitives get more defensible still: PostgreSQL, Kafka, Kubernetes, Linux, identity, durable execution. Their value is correctness under failure, learned through decades of incidents, and agents are their most demanding clients yet: tireless, parallel, retry-happy and wrong in untested ways. A 30-step agent loop resends its history every step, close to a million input tokens for one support ticket, and at 98% per-step reliability it finishes cleanly about 55% of the time. It needs idempotency keys on every write, per-agent quotas, durable workflows that survive a crash at step 23, an append-only log of every action, and a router that sends each step to the cheapest capable model.52 (We build these systems for customers, so we have a stake in this.) A bespoke world multiplies programs, and by Naur’s definition a program whose theory nobody holds is born dead. Naur said the theory can never be fully written down. Its most important part can: the invariants and the evals. Balances never go negative. Every message is delivered at least once. No user reads another tenant’s data. The evals are the part of the theory that survives the team. People own the spec, the evals and the signature; machines own the middle. When code is cheap and everyone has the aimer, the scarce skill is calling the pocket before the shot. For all of that, AI is still a stochastic parrot, a far better one, and we’re all training parrots, more or less: every eval, golden set and harness is a lesson. The next ones may be categorical parrots. Jev, from TypeSafe AI, never writes prose: it answers typed questions (true or false, a choice, a score) with probabilities its makers train to be calibrated, for software to act on, and it is named after Jevons, on the bet that cheaper judgment means far more of it.53 A parrot that answers in categories, with its confidence attached, is one you can check. The right tools in the right hands still make the difference, and the human edge shows in all the path-breaking work above. A person operated the system that resolved Erdős #728. A person built the harness that let sixteen agents write a compiler. People chose Navier–Stokes and the Riemann Hypothesis, and people are now digesting the proofs. So, was it worth it? The auto-aimer won me every game, and taught me the lesson that still applies: to bend a system, you first have to understand it. The machines draw every line now. Somebody still has to know where the ball needs to go, and put their name on the shot. Carlos E. Jimenez et al., “SWE-bench: Can Language Models Resolve Real-World GitHub Issues?,” arXiv:2310.06770, October 2023 (Claude 2, with BM25 retrieval). https://arxiv.org/abs/2310.06770 ↩ Bloomberg, “$335,000 Pay for ‘AI Whisperer’ Jobs Appears in Red-Hot Market,” 29 March 2023 (an Anthropic “prompt engineer and librarian” listing). https://www.bloomberg.com/news/articles/2023-03-29/ai-chatgpt-related-prompt-engineer-jobs-pay-up-to-335-000 ↩ Andrej Karpathy on X, 2 February 2025; Collins Dictionary made vibe coding its 2025 word of the year. https://knowyourmeme.com/memes/vibe-coding ↩ Dario Amodei at the Council on Foreign Relations, 10 March 2025, as reported by Fortune, 13 March 2025. https://fortune.com/2025/03/13/ai-transforming-software-development-jobs-meta-ibm-anthropic/ ↩ Peter Naur, “Programming as Theory Building,” Microprocessing and Microprogramming 15 (1985), pp. 253–261. https://pages.cs.wisc.edu/~remzi/Naur.pdf ↩ Merriam-Webster, “2025 Word of the Year: Slop,” December 2025. https://www.merriam-webster.com/wordplay/word-of-the-year ↩ Nataliya Kosmyna et al., “Your Brain on ChatGPT: Accumulation of Cognitive Debt when Using an AI Assistant for Essay Writing Task,” MIT Media Lab, arXiv:2506.08872, June 2025 (preprint, not peer-reviewed). https://www.media.mit.edu/publications/your-brain-on-chatgpt/ ↩ Anthropic, “Introducing Claude Opus 4.5,” 24 November 2025. The take-home result used parallel test-time compute; without a time limit the model matched the best-ever human candidate. Anthropic notes the exam doesn’t test collaboration or communication. https://www.anthropic.com/news/claude-opus-4-5 ↩ Nicholas Carlini, “Building a C compiler with a team of parallel Claudes,” Anthropic Engineering, 5 February 2026. https://www.anthropic.com/engineering/building-c-compiler ↩ ↩2 ↩3 METR, “Task-Completion Time Horizons of Frontier AI Models” (Time Horizon 1.1; last updated 8 September 2026). 95% intervals are wide: about 5 to 61 hours for Opus 4.6’s 50% horizon. https://metr.org/time-horizons/; data: https://metr.org/assets/benchmark_results_1_1.yaml ↩ ↩2 Sarah McLennan and Mary Gainer, “When the Computer Wore a Skirt: Langley’s Computers, 1935–1970,” NASA History. https://www.nasa.gov/history/when-the-computer-wore-a-skirt-langleys-computers-1935-1970/ ↩ Michael A. Cusumano, Japan’s Software Factories: A Challenge to U.S. Management, Oxford University Press, 1991. https://academic.oup.com/book/52424; on Hitachi specifically, Cusumano, “Hitachi: pioneering the ‘factory’ model for large-scale software development,” MIT Sloan working paper 1886-87, 1987. https://dspace.mit.edu/handle/1721.1/48050 ↩ On Dan Shapiro’s five levels and StrongDM’s no-human-written, no-human-reviewed rules, as summarised in Encyclopedia of Agentic Coding Patterns, “Dark Factory.” https://aipatternbook.com/dark-factory ↩ WBUR On Point, “Why the tech world is ‘tokenmaxxing’,” 28 April 2026. https://www.wbur.org/onpoint/2026/04/28/tokenmaxxing-how-tech-workers-are-gamifying-their-way-to-unemployment ↩ Jellyfish, “Is ‘tokenmaxxing’ cost effective? New data from Jellyfish explains,” 15 April 2026 (Q1 2026, 12,000 developers, 200 companies). https://jellyfish.co/blog/is-tokenmaxxing-cost-effective-new-data-from-jellyfish-explains/ ↩ METR, “Measuring the Impact of Early-2025 AI on Experienced Open-Source Developer Productivity,” 10 July 2025; arXiv:2507.09089. https://metr.org/blog/2025-07-10-early-2025-ai-experienced-os-dev-study/ ↩ METR, “We are Changing our Developer Productivity Experiment Design,” 24 February 2026. https://metr.org/blog/2026-02-24-uplift-update/ ↩ Google Cloud DORA, 2025 State of AI-assisted Software Development, September 2025, as summarised by InfoQ. https://www.infoq.com/news/2025/09/dora-state-of-ai-in-dev-2025; report: https://services.google.com/fh/files/misc/2025_state_of_ai_assisted_software_development.pdf ↩ Faros AI, “Tokenmaxxing: Why token consumption isn’t AI engineering productivity,” 23 April 2026 (two years of data, 22,000 developers, 4,000 teams). https://www.faros.ai/blog/tokenmaxxing ↩ Eliyahu M. Goldratt, The Goal (1984), the origin of the theory of constraints. https://en.wikipedia.org/wiki/Theory_of_constraints ↩ Veracode, “AI-Generated Code Poses Major Security Risks in Nearly Half of All Development Tasks,” 30 July 2025 (2025 GenAI Code Security Report). https://www.veracode.com/press-release/ai-generated-code-poses-major-security-risks-in-nearly-half-of-all-development-tasks-veracode-research-reveals/ ↩ Joseph Spracklen et al., “We Have a Package for You! A Comprehensive Analysis of Package Hallucinations by Code Generating LLMs,” USENIX Security 2025, as reported by SecurityWeek. https://www.securityweek.com/ai-hallucinations-create-a-new-software-supply-chain-threat/ ↩ Daniel Stenberg, “The end of the curl bug-bounty,” 26 January 2026. https://daniel.haxx.se/blog/2026/01/26/the-end-of-the-curl-bug-bounty/ ↩ XBOW, “XBOW tops US leaderboard on HackerOne,” June 2025; see also CSO Online, “The top red teamer in the US is an AI bot.” https://www.csoonline.com/article/4012801/the-top-red-teamer-in-the-us-is-an-ai-bot.html ↩ DARPA, “AI Cyber Challenge results,” 8 August 2025. https://darpa.mil/news/2025/aixcc-results ↩ Anthropic, “Disrupting the first reported AI-orchestrated cyber espionage campaign,” 13 November 2025 (attribution is Anthropic’s high-confidence assessment). https://www.anthropic.com/news/disrupting-AI-espionage ↩ CBS News, “Former Uber security chief sentenced for data-breach cover-up,” 4 May 2023 (conviction October 2022). https://www.cbsnews.com/sanfrancisco/news/former-uber-security-chief-sentenced-data-breach-cover-up/ ↩ Widely attributed to a 1979 IBM internal training slide, first shared online in February 2017. IBM’s archives have not located the original, which was reportedly destroyed in a flood. Simon Willison, “A computer can never be held accountable,” 3 February 2025. https://simonwillison.net/2025/Feb/3/a-computer-can-never-be-held-accountable/ ↩ Chris Newcombe et al., “How Amazon Web Services Uses Formal Methods,” Communications of the ACM 58(4), April 2015. https://cacm.acm.org/magazines/2015/4/184701-how-amazon-web-services-uses-formal-methods/fulltext ↩ Martin Kleppmann, “Prediction: AI will make formal verification go mainstream,” 8 December 2025. https://martin.kleppmann.com/2025/12/08/ai-formal-verification.html ↩ Sergiu Bursuc et al., “A benchmark for vericoding: formally verified program synthesis,” arXiv:2509.22908, September 2025. https://arxiv.org/abs/2509.22908 ↩ Nat Sothanaphan, “Resolution of Erdős Problem #728: a writeup of Aristotle’s Lean proof,” arXiv:2601.07421, January 2026. https://arxiv.org/abs/2601.07421 ↩ George Tsoukalas et al., “Advancing Mathematics Research with AI-Driven Formal Proof Search,” arXiv:2605.22763, May 2026. https://arxiv.org/abs/2605.22763 ↩ OpenAI, “On the Navier–Stokes Millennium Prize Problem,” 8 September 2026 (claims statements C and D of the official problem; Lean formalisation published). Verification status and the Clay Institute’s rules: Wikipedia, “Millennium Prize Problems”. https://openai.com/index/navier-stokes-solution/; https://en.wikipedia.org/wiki/Millennium_Prize_Problems ↩ Terence Tao, “Unforced Euler singularity, unforced Navier-Stokes singularity, and the Generalized Riemann Hypothesis,” 20 November 2026 (Tao describes the AI-generated proof as one of the Generalized Riemann Hypothesis). https://terrytao.wordpress.com/2026/11/20/unforced-euler-singularity-unforced-navier-stokes-singularity-and-the-generalized-riemann-hypothesis/ ↩ ↩2 ↩3 Lean and Mathlib communities, “Lean verification of the Riemann Hypothesis,” 21 November 2026. https://leanprover-community.github.io/blog/posts/riemann-hypothesis/ ↩ ↩2 GitHub, “Spec-driven development with AI: Get started with a new open source toolkit” (Spec Kit), September 2025; AWS’s Kiro IDE, July 2025, works from requirements, design and task files. Compared in Birgitta Böckeler, “Understanding Spec-Driven-Development: Kiro, spec-kit, and Tessl,” martinfowler.com. https://github.blog/ai-and-ml/generative-ai/spec-driven-development-with-ai-get-started-with-a-new-open-source-toolkit/; https://www.martinfowler.com/articles/exploring-gen-ai/sdd-3-tools.html ↩ Simon Willison, notes on FoundationDB’s simulation testing, 13 February 2024; Pierre Zemb, The FoundationDB Book, “Correct and robust, choose both”. https://simonwillison.net/2024/Feb/13/foundationdb/; https://pierrez.github.io/fdb-book/meet_fdb/correctess.html ↩ Larry Page, talk at the American Association for the Advancement of Science, 2007, as transcribed in “How Larry Page had correctly predicted in 2007 that increased computation instead of clever algorithms would lead to AI progress,” OfficeChai, 20 April 2026. https://officechai.com/ai/how-larry-page-had-correctly-predicted-in-2007-that-increased-computation-instead-of-clever-algorithms-would-lead-to-ai-progress/ ↩ W. Stanley Jevons, The Coal Question, 1865. The effect is now known as the Jevons paradox. https://en.wikipedia.org/wiki/Jevons_paradox ↩ Klarna, “Klarna AI assistant handles two-thirds of customer service chats in its first month,” press release, 27 February 2024, as reproduced by CIO Dive. https://www.ciodive.com/news/klarna-generative-ai-customer-service-call-center/709916/ ↩ Tech.co, “Klarna Reverses AI Customer Service Overhaul,” 20 May 2025, reporting Sebastian Siemiatkowski’s interview with Bloomberg. https://tech.co/news/klarna-reverses-ai-overhaul ↩ Moffatt v. Air Canada, 2024 BCCRT 149, British Columbia Civil Resolution Tribunal, 14 February 2024; damages, interest and fees totalled $812.02. Summary by Dunphy Best Blocksom. https://www.dww.com/articles/bc-tribunal-finds-air-canada-liable-for-inaccurate-advice-given-by-website-chatbot ↩ Erik Brynjolfsson, Bharat Chandar and Ruyu Chen, “Canaries in the Coal Mine? Six Facts about the Recent Employment Effects of Artificial Intelligence,” Stanford Digital Economy Lab, revised November 2025 (ADP payroll data). https://digitaleconomy.stanford.edu/publications/canaries-in-the-coal-mine ↩ Emily M. Bender, Timnit Gebru, Angelina McMillan-Major and Shmargaret Shmitchell, “On the Dangers of Stochastic Parrots: Can Language Models Be Too Big?,” FAccT ‘21, 2021. https://dl.acm.org/doi/10.1145/3442188.3445922 ↩ PYMNTS, “Forward-Deployed Engineers Emerge as One of AI’s Fastest-Growing Jobs,” 10 March 2026, citing the Financial Times (monthly listings up more than 800%, January to September 2025). https://www.pymnts.com/artificial-intelligence-2/2026/forward-deployed-engineers-emerge-as-one-of-ais-fastest-growing-jobs/ ↩ Jake Angelo, Fortune, 13 January 2026 (a Mercor spokesperson on 30,000 contractors hired in 2025; the company’s claim of about $2 million paid to experts daily). https://fortune.com/2026/01/13/will-ai-take-my-job-or-human-skills-protect-me-mercor-training-self-made-billionaires/ ↩ TechCrunch, “Silicon Valley bets big on ‘environments’ to train AI agents,” 16 September 2025. https://techcrunch.com/2025/09/16/silicon-valley-bets-big-on-environments-to-train-ai-agents/ ↩ BEA (Bureau d’Enquêtes et d’Analyses), final report on Air France 447, July 2012, as summarised by IEEE Spectrum, 10 July 2012. Full report: https://www.faa.gov/sites/faa.gov/files/f-cp090601.en_.pdf; summary: https://spectrum.ieee.org/riskfactor/aerospace/aviation/air-france-flight-447-crash-caused-by-a-combination-of-factors ↩ Fabrizio Dell’Acqua et al., “The Cybernetic Teammate: A Field Experiment on Generative AI Reshaping Teamwork and Expertise,” NBER Working Paper 33641, April 2025; published in Organization Science, 2026. https://www.nber.org/papers/w33641 ↩ Retool, “The build vs. buy shift,” 2026 survey of 817 builders (Retool sells tools for building internal software). https://retool.com/blog/ai-build-vs-buy-report-2026 ↩ Lingjiao Chen, Matei Zaharia and James Zou, “FrugalGPT: How to Use Large Language Models While Reducing Cost and Improving Performance,” arXiv:2305.05176, 2023. The 98% figure is the authors’ result on their benchmarks. https://arxiv.org/abs/2305.05176 ↩ TypeSafe AI, “Introducing System One Models & Jev,” September 2026; Rashi Shrivastava, “This $200 Million Startup Wants To Fix AI’s Overconfidence Problem,” Forbes, 15 September 2026; summarised in Wikipedia, “Jev (AI model)”. Architecture and training details are unpublished. https://typesafe.ai/blog/introducing-system-one-models-and-jev; https://en.wikipedia.org/wiki/Jev_(AI_model) ↩ --- # TechMart Enterprise Voice Agent: Building a Sovereign AI Voice Support System for Indian Telecom URL: https://platformatory.io/blog/techmart-telephony-ai/ Published: 2026-07-31 Authors: Ashmith N Shetty Categories: AI, Voice AI, LangGraph GitHub: https://github.com/Platformatory/techmart_telephony_ai Introduction Customer support has long been a bottleneck for e-commerce operations at scale. Long hold times, inconsistent resolution quality, and the operational cost of scaling human agents linearly with call volume are problems every consumer-facing business eventually confronts. The TechMart Enterprise Voice Agent was built to address this directly by offering a real-time, telephony-native AI agent capable of handling customer support calls end-to-end, in multiple native Indian languages, without a human in the loop unless explicitly required. This post walks through the reasoning behind the system, the problems it solves, the architectural decisions made along the way, the trade-offs we accepted, and where the project is headed next. About The TechMart Voice Agent is a voice AI system that bridges live telephone calls to a stateful, tool-calling LLM core. A caller dials a number, is greeted by the AI, and can ask about orders, products, policies, or file a complaint all through natural, low-latency conversation. The system runs on Vobiz.ai for telecom transport, Pipecat for real-time audio orchestration, LangGraph for conversational reasoning, and Sarvam AI for Indian-language speech services, backed by a ClickHouse-hosted vector and relational data layer. Technology Stack Layer Technology Role Justification API & Orchestration FastAPI Hosts webhooks, WebSocket endpoints, and the Admin CMS Native async support required for concurrent WebSocket audio streams without blocking Telecom Transport Vobiz.ai Bridges live phone calls to WebSocket audio streams India-hosted telecom provider; lower per-minute cost than prior alternative at scale Audio Pipeline Pipecat-AI Real-time voice orchestration: VAD, turn-taking, barge-in Purpose-built framework for real-time voice pipelines; avoids reimplementing solved audio-concurrency problems Reasoning Core LangGraph & LangChain Stateful, tool-calling conversational agent Typed, checkpointed state machine required for auditable, multi-turn tool execution — capabilities that are generally not available in flow-builder platforms Primary LLM Groq (llama-3.3-70b-versatile) [To be deprecated on August 16, 2026] Main reasoning and response generation Low-latency inference required to stay within phone-call response tolerances Summary LLM Groq (llama-3.1-8b-instant) [To be deprecated on August 16, 2026] Memory summarization and ticket generation Smaller model sufficient for low latency summarization, reducing cost Speech Services Sarvam AI (saaras:v3, bulbul:v3) Native Indian-language STT and TTS India-hosted; native support for Indian dialects without a separate translation layer Vector & Relational DB ClickHouse Hybrid fuzzy string + vector search, CRM, order and ticket storage Single engine supports both fast analytical queries and vector similarity search, avoiding a separate vector-DB dependency Local Embeddings Sentence-Transformers (all-MiniLM-L6-v2) CPU-bound embedding generation for search Local inference removes external embedding-API latency and dependency Observability Langfuse Full trace logging of reasoning and tool execution Required for post-hoc interpretability of autonomous tool-calling decisions Testing Pytest Automated API and graph-logic validation Standard, mature framework for both unit and async integration testing Purpose The purpose of this project was to build a support agent that behaves less like a scripted IVR system and more like a competent, empathetic human agent. The core functionalities aimed for were: Understands unstructured, natural speech in multiple Indian languages and dialects Retrieves accurate, grounded information from company data rather than hallucinating Maintains conversational memory across a multi-turn phone call Knows the boundary of its own authority and hands off to a human when required Does all of this within the latency tolerances of a live phone call, where even a one-second delay is perceptible and disruptive Core Problems Several different problems had to be solved simultaneously for this system to be viable: Latency under real-time constraints. Unlike chat-based AI, a phone call has no tolerance for typing indicators or thinking pauses. STT, reasoning, tool execution, and TTS all have to happen inside a window the human ear perceives as a natural pause. Grounding and hallucination control. A support agent that invents a return policy or misquotes a product price is worse than no agent at all. Responses about orders, products, policies, or any other queries must be derived from verified data, not from the model’s memory. Multilingual support without added latency. India’s customer base speaks across a dozen major languages. Running a separate translation layer before and after the LLM call would double round-trip latency. Turn-taking and interruption handling. Real conversations involve interruptions, backchannel words (for example: “yes”, “okay”), and overlapping speech. A naive system either talks over the user or gets derailed by every murmur. Secure, scoped data access. The agent must only ever access the calling customer’s own data, never another customer’s order history or personal information. This is non-trivial precisely because the LLM autonomously selects which tool to invoke and the system must structurally prevent it from controlling whose data that tool accesses. Data sovereignty and geopolitical dependency. A significant architectural concern was avoiding dependency on foreign-hosted AI infrastructure. Recent events such as a U.S. export-control action temporarily suspending access to certain frontier models for customers like the Claude Fable model outside the U.S. on June 13, 2026 demonstrated that AI services hosted and governed under a single foreign jurisdiction can become unavailable overnight due to policy decisions entirely outside a business’s control. For a customer facing support system, this is an unacceptable single point of failure. The project was therefore built with a long-term commitment to Indian-hosted and Indian-governed infrastructure wherever viable, so that continuity of service is not dependent on the regulatory posture of another country. Why Not a Ready-Made Platform (Plivo, Exotel AI Studio, and Similar) Several CPaaS providers now offer bundled conversational-AI layers atop their telecom infrastructure. These were evaluated and deliberately not adopted, for three technical reasons: Transport-layer providers do not offer reasoning-layer control. Bundled AI Studio products are typically flow-builders or fixed prompt templates over a third-party LLM. They do not expose a typed, checkpointed state machine, custom tool binding against a proprietary hybrid search layer, or state-level security guarantees such as server-side identity injection, where sensitive identifiers like customer IDs are injected directly by the framework at the tool-execution layer, invisible to and unmodifiable by the LLM. The caller cannot influence the injected identity; it is resolved server-side from the verified phone number. Our requirement was a fully owned and extensible reasoning core, not an AI feature layered onto a call-routing product. Vobiz is used strictly for telecom transport only. Data sovereignty cannot be delegated to a third-party integration. Bundled AI layers route conversation data through the provider’s own backend LLM integrations, typically foreign hosted, with no visibility or control over data flow. Owning the reasoning layer means every provider in the chain is a deliberate, auditable choice, and any single one can be swapped out without touching the rest of the system. The planned future migration from Groq’s models to Sarvam’s LLM is a direct example of this. Bundled pricing compounds cost at scale. Some products charge a markup on both the telecom leg and the AI leg as a single resold unit. Decoupling transport (Vobiz) from reasoning (self-hosted LangGraph core) eliminates this intermediary margin, leaving only raw call minutes and direct LLM cost. In summary, ready-to-use platforms optimize for rapid demonstration, not for organizations requiring ownership of grounding data, security guarantees, and infrastructure jurisdiction. The Core Dilemma The central tension in this project can be summarized as a conflict between reasoning capability and real-time responsiveness. The most capable reasoning models are also the slowest to respond, and the most reliable data retrieval methods (multi-step, exhaustive search) are also the most latency-expensive. Every architectural decision in this system is a negotiation between these two forces. The central question was to answer “How do we get a large language model to reason well over structured and unstructured company data, execute tool calls, and produce a spoken response, all while a human is holding a phone to their ear waiting for a reply?” A secondary dilemma sits underneath this: control versus autonomy. A conversational agent needs enough autonomy to handle open-ended requests, but a support agent handling real customer accounts needs hard, non-negotiable guardrails. It must never be able to act outside its authorized scope, regardless of what the conversation or the model’s own reasoning suggests. Conceptual Solutions To resolve these dilemmas, the following conceptual approaches were adopted: Streaming everything. Rather than waiting for a complete LLM response before speaking, the system streams tokens directly into the TTS engine as they are generated, and plays a language-appropriate filler phrase (for example, “Just a moment…” in English, or “एक सेकंड…” in Hindi) only if the model takes longer than 1.5 seconds to respond, thus masking latency rather than eliminating it. Retrieval over recall. All factual claims about products, policies, and orders are retrieved live from a database at inference time via tool calls, rather than relying on the model’s parametric memory. Hybrid search instead of pure vector search. Two independent searches run side by side on every query: a fuzzy string-matching search that catches typos and partial word matches (this measures how similar two strings look character-by-character, complementing term-frequency-based methods like BM25), and a vector similarity search that catches results that mean the same thing even when worded differently. The two ranked result lists are then merged using Reciprocal Rank Fusion which is a simple technique that combines rankings from multiple searches into a single, more reliable ranking. This catches more relevant results than either search could alone, without needing a larger, slower model. Native multilingual generation instead of translation pipelines. Sarvam AI’s STT engine transcribes the caller’s speech directly into native-language text (Hindi, Tamil, Kannada, and so on), which is passed to the LLM without any intermediate translation step. The LLM is instructed to write its tool call arguments in English, since the database schema requires English values, while writing its actual spoken reply in the caller’s detected language; that reply is then synthesized back to audio by Sarvam AI’s TTS engine. This removes an entire round-trip of translation latency that a pipeline approach would require. State-level security instead of prompt-level trust. Rather than trusting the LLM to correctly supply a customer ID in a tool call, sensitive identifiers are injected directly into the tool execution at the LangGraph ToolNode layer via LangGraph’s InjectedState mechanism, invisible to and unmodifiable by the model. Sovereign infrastructure by default. Preferring Indian-hosted and Indian-operated services for every layer of the stack that touches customer data or is critical to uptime, rather than defaulting to the most well-known global provider. The Core Architectural Decision The single most consequential decision in this project was to decouple the conversational “brain” from the audio transport layer entirely, using LangGraph as a swappable reasoning engine, built to look like an ordinary LLM service to the audio pipeline, even though a full agent is running underneath. Concretely: the audio pipeline (built on Pipecat) has no awareness that its “LLM” is actually a full LangGraph state machine with eight bound tools, a rolling memory summarizer, and a checkpointer. It only sees something that looks like an OpenAI-compatible chat service. This was achieved by subclassing Pipecat’s OpenAILLMService and overriding its context-processing method to instead stream events out of a compiled LangGraph graph. Simplified pattern class LangGraphAsLLMService(OpenAILLMService): async def _process_context(self, context): async for event in self.compiled_graph.astream(context): yield event # streamed to Pipecat as if from a normal LLM This decision had several downstream benefits: The reasoning core (LangGraph) can be tested, iterated on, and even swapped independently of the audio stack, via a text-only tester that bypasses telephony entirely. Pipecat’s native handling of interruption, barge-in, and TTFB metrics is inherited “for free,” without reimplementing turn-taking logic inside the LangGraph layer. The state machine itself is a single agent that reasons, calls a tool, reads the result, and reasons again in a loop (a “ReAct” pattern), rather than a multi-agent router. This is deliberately simple, because a multi-agent architecture (a router LLM dispatching to specialist sub-agents) would have added an extra reasoning hop, and therefore latency. The task is already operating under strict latency constraints, where the primary bottleneck is response time, not computational cost, and it isn’t complex enough to justify that additional overhead. Abbreviations Abbreviation Full Form BM25 Best Matching 25 CMS Content Management System CPaaS Communications Platform as a Service CRM Customer Relationship Management FAQ Frequently Asked Questions HTTP Hypertext Transfer Protocol IVR Interactive Voice Response LLM Large Language Model STT Speech-to-Text TTFB Time-To-First-Byte TTS Text-to-Speech VAD Voice Activity Detection Security & Data Isolation Because the agent handles live customer accounts over the phone, the system must guarantee that a caller can never access another customer’s data, regardless of how the conversation is steered. This is enforced structurally rather than through prompting: Server-side identity injection. When a call connects, the caller’s phone number is verified at the telecom layer and used to look up their record. Sensitive identifiers such as customer_id are then stored in the LangGraph agent state. They are never supplied by the LLM — instead, they are injected directly into tool execution at the LangGraph ToolNode layer via LangGraph’s InjectedState mechanism, so the model can request an action but cannot control whose data that action touches. Explicit confirmation gates. State-changing actions, such as filing a complaint ticket, require a two-step flow. First, an eligibility check runs; then the caller must explicitly confirm before any write occurs. Scoped admin access. The Admin CMS, used to manage catalog, FAQ, and policy data, sits behind API-key authentication, independent of the customer-facing call flow. This approach treats data isolation as a property of the system’s architecture, not of the model’s judgment. How Our Decisions Changed and Why Architecture is rarely right on the first attempt, and two decisions in particular evolved substantially over the course of building this system. Building the audio pipeline in-house, then adopting Pipecat. Our initial approach was to build the entire real-time audio pipeline ourselves. This meant manually managing the WebSocket audio stream, VAD, turn-taking logic, and the handoff between STT, LLM, and TTS stages. This consumed a disproportionate amount of engineering time relative to the value it produced, and introduced a steady stream of subtle bugs around audio buffering, race conditions between interruption events, and barge-in handling, problems that are well-understood and already solved in mature frameworks. We ultimately migrated to Pipecat-AI, a purpose-built framework for real-time voice AI pipelines. This let us inherit correct, battle-tested behavior for VAD, barge-in, and frame-based audio processing, and let our own engineering effort focus entirely on the reasoning layer. Migrating from Exotel to Vobiz.ai for telecom transport. The system originally used Exotel as the telephony provider bridging phone calls to our WebSocket infrastructure. After evaluating cost at projected call volumes, we migrated to Vobiz.ai, which offered materially better economics for the same core capability (bidirectional audio streaming over WebSockets with programmable call control). The interface contracts of both providers are similar enough that the migration was contained almost entirely to the transport/serialization layer, without touching the reasoning core. Interpretability A voice AI system making autonomous decisions about tool calls, ticket filing, and human handoffs cannot be a black box. Every decision the agent makes needs to be traceable after the fact, both for debugging and for accountability when a customer disputes what happened on a call. The interpretability challenge here is compounded by the real-time nature of the system: standard debugging techniques such as breakpoints are not viable here. Pausing execution mid-call would freeze the audio stream, causing the telephony bridge to time out and drop the call entirely. Interpretability has to be achieved through structured observability rather than interactive inspection. Addressing Interpretability These concrete mechanisms address this: Full tracing via Langfuse. Every graph invocation is wrapped in a Langfuse callback handler, capturing the complete chain of system prompt construction, tool calls, tool outputs, and final responses for every single turn of every call, allowing a full post-hoc reconstruction of why the agent said what it said. A structured, typed agent state. Because the LangGraph AgentState is a strictly typed dictionary (messages, customer_profile, handoff_status, user_emotion, summary, etc.) rather than a loose blob of context, every decision point in the conversation can be inspected as a discrete, named field rather than reverse-engineered from raw text. Non-negotiable tool boundaries as an interpretability aid, not just a security one. Because tools like raise_complaint_ticket receive their customer_id via InjectedState rather than LLM-generated arguments, any anomaly in a ticket can be immediately attributed to either the retrieval layer or the model’s reasoning, never to a spoofed or hallucinated identifier, which narrows the debugging surface considerably. Automatic call-ticket summarization. Every completed call is summarized into a structured ticket with an embedded vector, giving a permanent, searchable, human-readable record of what happened, independent of the raw trace logs. In short, we trade live interactive debugging for comprehensive after-the-fact tracing, so nothing needs to pause mid-call, but everything is fully reconstructable once the call is over. Scalability Several design choices in the current system were made specifically with horizontal scale in mind: Safe concurrent database access. ClickHouse’s HTTP client is not safe to share concurrently across calls in our current usage. To avoid this, each call gets its own dedicated database connection, and all database queries run on background threads, so a slow query never freezes the main event loop that’s handling live call audio. Stateless at the fleet level, stateful per call. A voice call is one long-lived WebSocket connection, so once a load balancer assigns it to a FastAPI instance, it stays on that same instance for the call’s entire duration. It never hops between instances mid-call. This lets that instance keep the call’s conversation history in fast, local in-memory storage instead of round-tripping to a database on every turn, with only a final summary written to ClickHouse once the call ends. What makes this scale horizontally is that no instance needs any special state before a call starts: a brand-new call can be handed to any instance, including one spun up moments ago with no prior setup or state-sharing required. Scaling out is therefore just adding more identical instances behind the load balancer. On a mid-call worker restart or failure, the in-memory conversation state for that instance is lost and the call must reconnect and re-establish context. Pre-warming on startup. All models (embeddings, sentiment classifier, VAD, LLM clients) are explicitly warmed up during the application lifespan startup event, ensuring the very first call handled by a newly spun-up instance is not penalized with cold-start latency. As call volume grows, the natural next steps are horizontal scaling of the FastAPI/Pipecat worker layer and a managed ClickHouse cluster with read replicas. Future Enhancements Full migration to Sarvam AI’s language models. The system currently uses Groq-hosted Llama models (llama-3.3-70b-versatile for reasoning, llama-3.1-8b-instant for summarization) as the primary and background LLMs, while already using Sarvam AI for STT and TTS. The next major architectural milestone is consolidating the reasoning layer itself onto Sarvam’s own sarvam-30b or sarvam-150b language models. This is a direct extension of our sovereignty principle: reducing our dependency footprint to a single, India-hosted provider across the entire voice-to-reasoning-to-voice pipeline, rather than spanning multiple providers across different jurisdictions. Deeper personalization via customer history. Expanding get_customer_history retrieval to proactively inform the agent’s opening approach on a call, rather than only being queried reactively. Expanded human-handoff intelligence. Moving beyond explicit user request as the sole handoff trigger, toward confidence-based escalation when the agent’s own retrieval results are weak or ambiguous. Multi-region ClickHouse deployment. As call volume grows across different regions of India, deploying regional ClickHouse read replicas to reduce database round-trip latency for geographically distributed calls. Closing Note The TechMart Voice Agent was built on a simple premise: a support agent should be fast, accurate, accountable, and it should not become unavailable because of a regulatory or policy decision made in a jurisdiction the business has no relationship with. Every architectural choice documented here, from the LangGraph-as-LLM-service pattern to the shift toward fully Indian-hosted infrastructure, traces back to that premise. --- # Streaming Kafka Data into Oracle: JDBC Sink Connector, Upserts, and LOB Handling URL: https://platformatory.io/blog/Streaming-Kafka-Data-Into-Oracle/ Published: 2026-07-18 Authors: Balaji K Categories: Kafka Connect, Oracle, Kafka, Data Engineering Introduction In many data streaming projects, the first milestone is to capture data from a source system and publish it into Kafka. But the data movement story often does not stop there. Once data is available in Kafka topics, downstream systems need to consume it. One common requirement is to synchronize data from Kafka topics into an Oracle database. This may be required for operational reporting, downstream application integration, database modernization, audit stores, or cross-zone database synchronization. At first, this sounds simple:   Kafka Topic –> JDBC Sink Connector –> Oracle Database For simple data types such as VARCHAR2, NUMBER, DATE, and TIMESTAMP, this is usually straightforward if the Kafka record schema, primary key strategy, and destination table are designed properly. However, the challenge increases when Kafka topics contain LOB data such as BLOB, CLOB, NCLOB. LOB data may arrive as bytes, Base64-encoded content, or binary Avro payloads, depending on the converter and source connector behavior. If the destination Oracle table expects a readable CLOB or NCLOB, the pipeline may need transformation before the JDBC Sink Connector writes the data. This blog focuses on the Kafka-to-Oracle side of the pipeline: how to write Kafka records into Oracle using the Confluent JDBC Sink Connector and how to handle LOB columns safely. The Use Case The high-level requirement is to synchronize data from Kafka topics into Oracle tables. In a CDC-based architecture, these Kafka topics may have been produced by an upstream CDC source connector. For example: This blog focuses only on the second half: Kafka Topics –> Oracle Destination DB The important question is: How do we correctly map Kafka records into Oracle table rows, especially when LOB columns are involved? Why Use JDBC Sink Connector? The JDBC Sink Connector is commonly used when Kafka topic records need to be written into relational databases. It provides a standard Kafka Connect based mechanism for: Consuming Kafka records Mapping record fields to database columns Inserting rows Updating rows Performing upserts Managing retries Handling errors Using Single Message Transforms Integrating with schema-aware converters Instead of writing a custom Kafka consumer application for every database synchronization requirement, the JDBC Sink Connector provides a reusable integration pattern. Basic Kafka-to-Oracle Flow For a simple Kafka topic containing customer data, the flow may look like this: Destination Oracle table: 1 2 3 4 5 CREATE TABLE CUSTOMER ( CUSTOMER_ID NUMBER PRIMARY KEY, NAME VARCHAR2(100), STATUS VARCHAR2(20) ); For this type of record, the sink connector can map fields directly to columns. Conceptually: 1 2 3 Kafka field CUSTOMER_ID -> Oracle column CUSTOMER_ID Kafka field NAME -> Oracle column NAME Kafka field STATUS -> Oracle column STATUS INSERT, UPDATE and UPSERT One of the most important design decisions is how records should be written into Oracle. Common modes are: Insert Update Upsert Insert Mode insert mode is useful when every Kafka record represents a new row. Example: 1 insert.mode=insert This is simple, but it can fail if a row with the same primary key already exists. Update Mode update mode is useful when rows already exist in the destination table and Kafka records should update those rows. Example: 1 insert.mode=update This requires the destination row to already exist. Upsert Mode upsert mode is usually preferred for synchronization use cases. Example: 1 insert.mode=upsert In this mode: 1 2 If the row exists -> Update it If the row is absent -> Insert it For database synchronization, this is often the most practical behavior. Primary Key Handling Upsert requires a reliable primary key. The JDBC Sink Connector needs to know which field or fields identify the destination row. Example Oracle table: 1 2 3 4 5 CREATE TABLE CUSTOMER ( CUSTOMER_ID NUMBER PRIMARY KEY, NAME VARCHAR2(100), STATUS VARCHAR2(20) ); The Kafka record must either have the primary key in the key or in the value. Example where primary key is in value: 1 2 3 4 5 { "CUSTOMER_ID": 101, "NAME": "John Doe", "STATUS": "ACTIVE" } Typical connector configuration pattern: 1 2 3 insert.mode=upsert pk.mode=record_value pk.fields=CUSTOMER_ID This tells the sink connector to use the CUSTOMER_ID field from the Kafka record value as the primary key. Without correct key handling, the connector may not be able to update existing rows reliably. Auto-Create Table vs Pre-Created Oracle Table The JDBC Sink Connector can create tables automatically in some cases if auto.create=true is configured. However, for Oracle production workloads, especially where LOB columns are involved, it is usually better to pre-create the destination table. Reasons: You can control exact Oracle data types You can define primary keys explicitly You can choose CLOB vs NCLOB vs BLOB correctly You can define indexes and constraints properly You can avoid incorrect type inference You can align storage, tablespace, and LOB segment settings For example, if the Kafka field is represented as bytes, automatic table creation may not infer the desired Oracle NCLOB type. You may need the destination column to be explicitly defined. Example: 1 2 3 4 5 6 CREATE TABLE EMPLOYEE ( ID NUMBER PRIMARY KEY, NAME VARCHAR2(100), UPDATED_AT TIMESTAMP, NOTES NCLOB ); In this case, you want the sink pipeline to write decoded text into NOTES, not raw bytes. Kafka Connect Type to Oracle Column Mapping Before deploying the sink connector, review how Kafka Connect field types should map to Oracle columns. A practical mapping table: 1 2 3 4 5 6 7 8 9 10 11 Kafka Connect Type Suggested Oracle Type Notes --------------------- ------------------------- ----------------------- String VARCHAR2 / CLOB / NCLOB Depends on size and encoding Int8 / Int16 / Int32 NUMBER Validate range Int64 NUMBER Validate range Float32 / Float64 FLOAT / BINARY_FLOAT / NUMBER Depends on precision need Decimal NUMBER(p,s) Validate precision and scale Boolean NUMBER(1) or CHAR(1) Oracle has no native boolean column in SQL tables Date DATE Confirm date semantics Timestamp TIMESTAMP Confirm timezone requirements Bytes RAW / BLOB / CLOB / NCLOB Depends on actual payload meaning The most important row is Bytes. A Kafka Bytes field does not automatically tell you whether the data is: 1 2 3 4 5 6 Binary file content UTF-8 encoded text UTF-16 encoded NCLOB text Base64-encoded JSON representation XML payload Compressed binary content You must know what the bytes represent before writing them into Oracle. Primitive Column Handling For primitive columns, the Kafka-to-Oracle flow is usually straightforward. Example Kafka record: 1 2 3 4 5 6 { "ID": 101, "NAME": "John Doe", "AMOUNT": 2500.75, "CREATED_AT": "2026-07-10T10:15:30" } Destination Oracle table: 1 2 3 4 5 6 CREATE TABLE PAYMENT_EVENT ( ID NUMBER PRIMARY KEY, NAME VARCHAR2(100), AMOUNT NUMBER(12,2), CREATED_AT TIMESTAMP ); The main checks are: 1 2 3 4 5 6 - Does the Kafka field name match the Oracle column name? - Does the data type match? - Is precision and scale correct for NUMBER columns? - Is timestamp precision acceptable? - Are nullable fields handled correctly? - Is the primary key available? Why LOB Columns Need Special Handling LOB stands for Large Object. Oracle supports: 1 2 3 BLOB -> Binary Large Object CLOB -> Character Large Object NCLOB -> Unicode / national character large object LOB columns are used for: 1 2 3 4 5 6 7 8 - Large text - XML - JSON - Documents - PDF files - Images - Binary payloads - Application notes or comments From a sink perspective, the issue is not only size. The bigger issue is representation. A Kafka topic may contain LOB data as: 1 2 3 4 5 6 - Raw bytes - Avro bytes - Base64-encoded JSON string - UTF-16 byte array - UTF-8 text - Nested structure containing LOB metadata and payload Before writing into Oracle, you need to answer: 1 2 3 4 5 6 - Is this payload binary or text? - If text, what encoding is used? - Should the destination column be CLOB or NCLOB? - Does the value need decoding? - Does the value contain null characters? - Does the sink connector receive the final value in the correct field? BLOB vs CLOB vs NCLOB Handling BLOB BLOB is binary data. If the Kafka field is truly binary content, it can remain as bytes. Example use cases: 1 2 3 4 PDF Image Compressed file Binary document Typical handling: 1 Kafka bytes field --> JDBC Sink Connector --> Oracle BLOB column For BLOBs, do not try to decode the bytes as a string unless you are certain the bytes represent text. CLOB CLOB is character data. It is used for large text based on the Oracle database character set. Example use cases: 1 2 3 4 - Large text - JSON document - XML document - Application notes If Kafka already contains the value as a string, the JDBC Sink Connector may be able to write it directly to a CLOB column. But if Kafka contains the value as bytes, you need to decode it into a string first. Typical handling: 1 Kafka bytes field --> Decode using correct character set --> String value --> Oracle CLOB column NCLOB NCLOB is used for Unicode national character data. In Oracle, NCLOB commonly uses AL16UTF16, which corresponds to UTF-16 Big Endian. If the Kafka topic contains raw NCLOB bytes, the sink pipeline may need to decode those bytes using UTF-16 Big Endian before writing to Oracle. Typical handling: 1 Kafka LOB topic --> Read byte[] --> Decode UTF-16 Big Endian to String --> Remove null characters if required --> Write String to Oracle NCLOB column Example: Kafka Topic to Oracle Table with NCLOB Destination Oracle table: 1 2 3 4 5 6 CREATE TABLE EMPLOYEE ( ID NUMBER PRIMARY KEY, NAME VARCHAR2(100), UPDATED_AT TIMESTAMP, NOTES NCLOB ); Primitive Kafka topic record: 1 2 3 4 5 { "ID": 101, "NAME": "John Doe", "UPDATED_AT": "2026-07-10T10:15:30" } LOB Kafka topic record, conceptually: 1 2 3 4 { "ID": 101, "NOTES": "" } The primitive fields can be written directly. The NOTES field needs special handling: 1 2 3 4 NOTES bytes -> decode UTF-16 -> clean string -> write to Oracle NCLOB Recommended LOB Processing Pattern A clean production pattern is to separate primitive and LOB processing. This separation gives you better control and easier troubleshooting. Using SMTs for LOB Transformation Kafka Connect Single Message Transforms, or SMTs, can modify records before they are written by the sink connector. For LOB handling, a custom SMT may be used to: 1 2 3 4 5 6 7 - Read raw byte[] field - Decode bytes using UTF-16 Big Endian - Remove null characters - Trim or normalize text if required - Move the decoded value into the expected field name - Drop unnecessary metadata fields - Prepare the record for JDBC Sink Connector Conceptual example: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 Input record: { "ID": 101, "NOTES": } Custom SMT processing: - Extract NOTES as byte[] - Decode using UTF-16BE - Remove null characters - Replace NOTES with decoded String Output record: { "ID": 101, "NOTES": "Employee profile updated with additional remarks" } After this, the JDBC Sink Connector sees NOTES as a string and can write it to the Oracle NCLOB column. When SMT Is Not Enough SMTs are useful for simple record-level transformations. However, they are not always the best option. Use Kafka Streams, Flink, or another stream processor when you need: 1 2 3 4 5 6 7 Join primitive topic and LOB topic Maintain state Handle ordering between primitive and LOB events Perform complex enrichment Merge multiple LOB columns into one output record Validate or repair records Handle multi-step transformation logic For example, if primitive data and LOB data arrive in separate Kafka topics and need to be merged before writing to Oracle, a stream processing application may be more suitable than an SMT. Handling Separate LOB Topics In some CDC flows, primitive columns and LOB columns are published into separate topics. Example: 1 2 3 4 5 Primitive topic: ORCL.ADMIN.EMPLOYEE LOB topic: EMPLOYEE-NOTES-lob There are two common sink patterns. Pattern 1: Two Sink Connectors to the Same Table Both sink connectors use the same primary key and upsert mode. This pattern works when the primitive and LOB updates can be applied independently. Pattern 2: Merge First, Then Sink This pattern is better when the destination row must be written as a complete merged record. JDBC Sink Connector Configuration Example A simplified JDBC Sink Connector configuration for primitive data may look like this: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 { "name": "oracle-employee-sink", "config": { "connector.class": "io.confluent.connect.jdbc.JdbcSinkConnector", "tasks.max": "1", "topics": "ORCL.ADMIN.EMPLOYEE", "connection.url": "jdbc:oracle:thin:@//oracle-host:1521/ORCLPDB1", "connection.user": "DEST_USER", "connection.password": "********", "insert.mode": "upsert", "pk.mode": "record_value", "pk.fields": "ID", "table.name.format": "EMPLOYEE", "auto.create": "false", "auto.evolve": "false" } } For LOB data, the connector may need a transform before writing: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 { "name": "oracle-employee-notes-lob-sink", "config": { "connector.class": "io.confluent.connect.jdbc.JdbcSinkConnector", "tasks.max": "1", "topics": "EMPLOYEE-NOTES-lob", "connection.url": "jdbc:oracle:thin:@//oracle-host:1521/ORCLPDB1", "connection.user": "DEST_USER", "connection.password": "********", "insert.mode": "upsert", "pk.mode": "record_value", "pk.fields": "ID", "table.name.format": "EMPLOYEE", "auto.create": "false", "auto.evolve": "false", "transforms": "DecodeNclob", "transforms.DecodeNclob.type": "com.example.kafka.connect.transforms.Utf16BytesToString$Value", "transforms.DecodeNclob.field": "NOTES" } } The transform class above is only an example. In a real implementation, the custom SMT must be written, packaged, deployed to the Kafka Connect plugin path, and tested. Error Handling and DLQ LOB processing can fail due to bad bytes, unexpected encoding, null values, unsupported payload structure, or destination column constraints. A production sink connector should have clear error handling. Recommended considerations: 1 2 3 4 5 6 7 Enable error tolerance only when appropriate Route failed records to a DLQ Capture error context and headers Log transformation errors clearly Monitor DLQ topic Create replay procedure for corrected records Do not silently skip failed LOB records Example configuration pattern: 1 2 3 4 5 errors.tolerance=all errors.deadletterqueue.topic.name=oracle-employee-sink-dlq errors.deadletterqueue.context.headers.enable=true errors.log.enable=true errors.log.include.messages=true Use this carefully. errors.tolerance=all should not become a way to hide data loss. It should be paired with monitoring and alerting. Testing Strategy Testing Kafka-to-Oracle synchronization should include more than one happy-path record. Test Primitive Data Validate: 1 2 3 4 5 6 7 8 Insert Update Upsert Null values Decimal precision Timestamp precision Primary key mapping Column name mapping Test LOB Data Validate: 1 2 3 4 5 6 7 8 9 10 Small LOB values Large LOB values Null LOB values Unicode characters Special characters Multi-byte characters LOB updates LOB deletes or nullification Very large payloads Invalid byte sequences Test Operational Scenarios Validate: 1 2 3 4 5 6 7 8 Connector restart Task failure and recovery DLQ handling Duplicate record processing Out-of-order primitive and LOB events Destination database outage Network failure Schema evolution Common Mistakes to Avoid Mistake 1: Relying on Auto-Create for Oracle LOB Tables Auto-created tables may not use the exact Oracle types you need. For LOB workloads, pre-create destination tables. Mistake 2: Treating Bytes as Text Without Decoding If Kafka contains byte[], do not assume it is already a string. Ask: 1 2 3 4 What produced these bytes? Are they binary or character data? Which character set was used? Should the target column be BLOB, CLOB, or NCLOB? Mistake 3: Ignoring NCLOB Encoding NCLOB values may require UTF-16 decoding. If you decode them incorrectly, the destination value may be corrupted. Mistake 4: Not Testing Large Values A 20-character test string does not prove LOB handling works. Test realistic LOB sizes. Mistake 5: Not Designing Key Strategy For upsert into Oracle, the sink must know the primary key. Always confirm: 1 2 3 4 Kafka key or value contains the key pk.mode is correct pk.fields is correct Destination table has matching primary key or unique constraint Recommended Pre-Implementation Checklist Before deploying the Kafka-to-Oracle sink pipeline, review the following: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 1. Kafka topic name 2. Kafka record format 3. Key location: record key or record value 4. Destination Oracle schema and table 5. Primary key mapping 6. Insert/update/upsert behavior 7. Column name mapping 8. Kafka Connect type to Oracle type mapping 9. LOB column list 10. LOB encoding 11. Required SMTs or stream processing 12. Error handling and DLQ 13. Retry behavior 14. Connector restart behavior 15. Monitoring and alerting For each table, create a mapping sheet like this: 1 2 3 4 5 6 7 Kafka Field | Kafka Type | Oracle Column | Oracle Type | Transformation Required | Notes ------------|------------|---------------|-------------|-------------------------|------ ID | Decimal | ID | NUMBER | No | Primary key NAME | String | NAME | VARCHAR2 | No | - UPDATED_AT | Timestamp | UPDATED_AT | TIMESTAMP | Validate precision | - NOTES | Bytes | NOTES | NCLOB | Decode UTF-16 | LOB FILE_DATA | Bytes | FILE_DATA | BLOB | No if true binary | Preserve bytes Recommended Architecture Choose the pattern based on ordering requirements, merge requirements, and downstream consistency expectations. Lessons Learned 1. Kafka-to-Oracle Sync Is Not Just a Sink Connector Configuration The connector is important, but the full design includes schema mapping, primary key strategy, converter behavior, destination table design, LOB handling, error handling, and operational monitoring. 2. Pre-Create Oracle Tables for Better Control For production workloads, especially with LOB columns, pre-create Oracle tables instead of relying on automatic table creation. 3. LOB Data Must Be Understood Before Writing A Kafka bytes field may represent binary data, UTF-8 text, UTF-16 text, XML, JSON, or another structure. The sink pipeline must know what the payload means. 4. NCLOB Requires Encoding Awareness If NCLOB data arrives as UTF-16 bytes, decode it correctly before writing it into Oracle as text. 5. Separate Primitive and LOB Handling When Required Trying to force all columns through one generic pipeline can make troubleshooting difficult. Separate primitive and LOB handling gives better control. Conclusion Synchronizing data from Kafka topics into Oracle using the JDBC Sink Connector is a powerful and reusable pattern. For simple relational columns, the flow is usually straightforward: map Kafka fields to Oracle columns, define primary key handling, choose insert/update/upsert behavior, and write records to the destination table. LOB columns require more careful design. BLOB, CLOB, NCLOB, and XMLTYPE should not be treated as ordinary fields without understanding their representation in Kafka. A bytes field may need to remain binary for a BLOB, or it may need to be decoded into a string for a CLOB or NCLOB. For NCLOB, UTF-16 decoding may be required before writing into Oracle. A reliable Kafka-to-Oracle synchronization pipeline should therefore include: 1 2 3 4 5 6 7 8 Correct topic-to-table mapping Reliable primary key strategy Explicit Oracle destination table design Data type review LOB-specific transformation where needed DLQ and error handling Operational monitoring Realistic testing with production-like data In short, the JDBC Sink Connector can move the data, but the pipeline design must preserve the meaning of the data. This is especially true for LOB columns, where correct encoding, transformation, and destination column design make the difference between a working synchronization pipeline and silent data corruption. --- # Demystifying Oracle CDC with Confluent: How Database Changes Flow into Kafka URL: https://platformatory.io/blog/Demystifying-Oracle-CDC-with-Confluent-Database-Kafka-Changes/ Published: 2026-07-10 Authors: Balaji K Categories: CDC, Oracle, Kafka Connect, Kafka Introduction Modern data platforms increasingly depend on real-time or near-real-time data movement. Traditional batch-based ETL still has its place, but for many use cases such as operational reporting, downstream synchronization, audit pipelines, fraud detection, and event-driven applications, waiting for hourly or daily jobs is no longer sufficient. This is where Change Data Capture (CDC) becomes important. CDC allows applications and data platforms to capture changes from a database as they happen and publish those changes to downstream systems. In the Oracle ecosystem, this is commonly done by reading database redo logs and converting committed database changes into events. In this blog, we will look at how data moves from Oracle DB to Kafka using the Confluent Oracle CDC Source Connector. We will also discuss what happens internally at a high level, what to check in Oracle table structures before implementing CDC, how different Oracle data types are represented in Kafka Connect, and why LOB columns such as BLOB, CLOB, and NCLOB require special attention. This article is based on a practical Oracle CDC implementation where Oracle source data, including primitive columns and NCLOB data, was streamed through Confluent Platform using Kafka Connect, Kafka topics, Schema Registry, and downstream sink processing. What Problem Are We Solving? The use case is simple to describe: Instead of writing custom jobs that repeatedly query Oracle tables, CDC captures row-level changes from Oracle and publishes those changes into Kafka topics. Once the data is in Kafka, multiple consumers can independently process it. One consumer may write the data into another Oracle database. Another may push it to a data lake. Another may enrich it and serve a real-time application. This is the major benefit of using Kafka for CDC: Oracle is no longer tightly coupled to every downstream system. Why Use Confluent Oracle CDC Source Connector? There are multiple ways to move Oracle data into Kafka. You could use polling queries, JDBC Source Connector, application-side publishing, Oracle GoldenGate, or custom PL/SQL-based jobs. However, for log-based CDC into Kafka, Confluent Oracle CDC Source Connector provides a purpose-built approach. The main reasons to choose it are: 1. It Captures Changes from Oracle Redo Logs Oracle records database changes in redo logs. The Confluent Oracle CDC Source Connector uses Oracle LogMiner to interpret those redo logs and identify committed changes. This avoids repeatedly querying source tables. With query-based polling, you usually depend on columns such as LAST_UPDATED_DATE or incrementing IDs. That approach can miss deletes, can miss certain updates, and usually adds extra read load on source tables. CDC through redo logs is a better fit when the requirement is to capture actual database changes. 2. Integration with Kafka Connect Kafka Connect provides the runtime for running the connector. This gives you a standard framework for: 1 2 3 4 5 6 7 8 - Connector deployment - Task execution - Offset tracking - Error handling - Converters - Single Message Transforms - Monitoring - Restart and recovery This means you are not building a custom data movement service from scratch. You are deploying a connector into a managed runtime that is already designed for streaming integration workloads. 3. It Publishes Database Changes as Kafka Events Once the connector processes Oracle redo log information, it produces records into Kafka topics. A common topic pattern is: 1 .. For example: 1 2 3 ORCL.ADMIN.USERS ORCL.ADMIN.ORDERS ORCL.ADMIN.CUSTOMERS This table-specific topic design makes downstream consumption easier. Consumers can subscribe only to the tables they care about. 4. It Allows Downstream Decoupling After Oracle changes are written to Kafka, many downstream systems can consume the same data independently: This is different from point-to-point database integration. Kafka becomes the central event backbone. 5. It Supports Schema-Aware Pipelines When used with Schema Registry and converters such as Avro, JSON Schema, or Protobuf, CDC records can carry structured schemas. This is important because CDC pipelines are not only moving data values, they are also moving the structure and meaning of the data. For example: 1 2 3 4 Oracle NUMBER -> Kafka Connect Decimal Oracle VARCHAR2 -> Kafka Connect String Oracle DATE -> Kafka Connect Date Oracle BLOB/CLOB -> Kafka Connect Bytes Schema awareness helps consumers understand the data format and reduces the risk of silent schema mismatches. High-Level Internal Working of Oracle CDC Source Connector At a high level, the data movement from Oracle to Kafka happens in multiple stages. 1 2 3 4 5 6 7 8 9 1. Application changes data in Oracle table 2. Oracle writes change information into redo logs 3. LogMiner reads and interprets redo logs 4. Oracle CDC Source Connector processes LogMiner output 5. Connector writes raw redo log events to a redo log topic 6. Connector converts changes into table-specific Kafka records 7. Records are serialized using configured converter 8. Data lands in Kafka topics 9. Consumers or sink connectors read from Kafka topics A simplified diagram: In the reference implementation, Oracle DB fed redo logs into the Oracle CDC Source Connector running inside Kafka Connect. The connector used LogMiner, wrote raw redo log events to a redo log topic, and then produced table-specific topics for primitive columns and separate LOB topics for LOB columns. Understanding the Redo Log Topic One important internal concept is the redo log topic. The connector does not simply read a table and directly publish rows to Kafka. It works from Oracle redo log information. A simplified view: The redo log topic acts as an intermediate Kafka topic containing raw redo log events. The connector processes this information and generates structured change events for the captured tables. This design helps the connector manage CDC processing, offsets, and table-level event generation. Table-Specific Topics For regular table columns, the connector produces data into table-specific topics. Example: 1 2 3 4 5 Oracle Table Kafka Topic ------------------------------------------------ ORCL.ADMIN.USERS ---> ORCL.ADMIN.USERS ORCL.ADMIN.ORDERS ---> ORCL.ADMIN.ORDERS ORCL.ADMIN.CUSTOMERS ---> ORCL.ADMIN.CUSTOMERS The topic naming can usually be controlled through connector configuration, such as a table topic name template. Example: 1 table.topic.name.template=${fullyQualifiedTableName} This means each Oracle table gets its own Kafka topic based on the fully qualified table name. This is clean and intuitive for downstream consumers because each table becomes a separate event stream. What Actually Flows into Kafka? A CDC event usually represents a database change. Depending on the connector configuration, converter, and event format, a Kafka record may include: 1 2 3 4 5 6 7 - Primary key - Changed row values - Operation type - Timestamp information - Source metadata - Schema information - Before/after values depending on configuration For example, an insert into an Oracle table: 1 2 INSERT INTO ADMIN.USERS (ID, NAME, STATUS) VALUES (101, 'John Doe', 'ACTIVE'); May become a Kafka event conceptually like: 1 2 3 4 5 { "ID": 101, "NAME": "John Doe", "STATUS": "ACTIVE" } For an update: 1 2 3 UPDATE ADMIN.USERS SET STATUS = 'INACTIVE' WHERE ID = 101; The event may represent the changed state of the row, depending on connector behavior and configuration. The exact message structure depends on the converter and connector settings, but the core idea is the same: database row-level changes become Kafka records. Why Table Design Matters Before Implementing CDC Before enabling CDC on Oracle tables, it is important to inspect the table design. Not all tables are equally easy to stream. At minimum, you should review: 1 2 3 4 5 6 7 8 9 10 11 12 - Primary key availability - Column data types - LOB columns - Nullable columns - Timestamp columns - Precision and scale for NUMBER columns - Character set and national character set - Unsupported or complex data types - Expected row size - Expected change volume - Delete behavior - Schema evolution frequency Let us look at the most important checks. Check 1: Does the Table Have a Primary Key? For CDC, primary keys are extremely important. A primary key helps downstream systems identify which row changed. For example: 1 2 3 4 5 CREATE TABLE CUSTOMER ( CUSTOMER_ID NUMBER PRIMARY KEY, NAME VARCHAR2(100), STATUS VARCHAR2(20) ); This is CDC-friendly because CUSTOMER_ID uniquely identifies the row. Without a primary key, downstream systems may struggle with updates and deletes. Sink connectors also need a reliable key when using upsert mode. For example, when writing to a destination Oracle table using JDBC Sink Connector: 1 insert.mode=upsert The sink needs to know which column or columns represent the key. Without that, the sink may not be able to update existing rows correctly. Before implementing CDC, always ask: 1 2 3 4 Does the table have a primary key? If not, is there a unique key? Can a stable business key be used? How will updates and deletes be handled downstream? Check 2: What Data Types Are Present? The next important check is column data types. Simple columns are usually straightforward: 1 2 3 4 - VARCHAR2 - NUMBER - DATE - TIMESTAMP Complex or sensitive columns need more attention: 1 2 3 4 5 6 7 8 - BLOB - CLOB - NCLOB - XMLTYPE - RAW - NUMBER with high precision - TIMESTAMP WITH TIME ZONE - TIMESTAMP WITH LOCAL TIME ZONE Example Oracle-to-Kafka Connect mappings: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Oracle Type Kafka Connect Mapping ---------------------------------------------------------- CHAR / VARCHAR / VARCHAR2 String NCHAR / NVARCHAR2 String RAW Bytes SMALLINT / DECIMAL / NUMBER Decimal DOUBLE PRECISION / FLOAT / REAL Float64 TIMESTAMP WITH TIMEZONE Timestamp TIMESTAMP WITH LOCAL TIME ZONE Timestamp DATE Date BLOB Bytes CLOB Bytes NCLOB Bytes XMLTYPE Bytes This is a critical point. Many teams assume that CLOB and NCLOB will appear as normal strings in Kafka. In practice, they appear as bytes and require additional handling. Check 3: Are There LOB Columns? LOB stands for Large Object. Oracle supports different LOB types: 1 2 3 BLOB -> Binary Large Object CLOB -> Character Large Object NCLOB -> National Character Large Object / Unicode character large object LOBs are used for large text, documents, XML, JSON, images, PDFs, and other large values. From a CDC point of view, LOBs are different from primitive columns because they are stored differently inside Oracle. Primitive Columns vs LOB Columns Consider this table: 1 2 3 4 5 CREATE TABLE EMPLOYEE ( ID NUMBER, NAME VARCHAR2(100), NOTES NCLOB ); The primitive columns are: 1 2 ID NAME The LOB column is: 1 NOTES Primitive columns are stored inline with the row. Conceptually: 1 2 3 4 Table Data Block ------------------------------------------------ Row: ID=101, NAME='John Doe', NOTES=[LOB LOCATOR] ------------------------------------------------ The row does not store the full NCLOB value directly. Instead, the row stores a LOB locator. The actual LOB content is stored separately in a LOB segment. 1 2 3 4 5 6 Separate LOB Segment ------------------------------------------------ LOB Chunk 1: "This is test data for NCLOB..." LOB Chunk 2: "...continued large text..." LOB Chunk 3: "...more text..." ------------------------------------------------ This difference matters because Oracle redo logs also represent LOB changes differently. Why LOB Columns Are Challenging in CDC For primitive columns, LogMiner can provide clean values that the connector can map to Kafka Connect data types. For example: 1 2 3 NUMBER -> Decimal VARCHAR2 -> String DATE -> Date For LOB columns, the connector may receive raw byte arrays. The reason is that LOB content is written into redo logs as binary chunks related to the LOB segment. It is not always represented as a simple readable SQL string. A simplified flow: This creates a downstream challenge. If the target database expects a readable NCLOB value, the pipeline may need to decode the byte array into a string before writing it. LOB Topic Handling The connector can produce separate LOB topics using a LOB topic name template. Example: 1 lob.topic.name.template=${tableName}-${columnName}-lob Example mappings: 1 2 3 4 5 Oracle Table / Column Kafka LOB Topic --------------------------------------------------- ORCL.ADMIN.NOTES ---> ADMIN-NOTES-lob ORCL.ADMIN.ATTRS ---> ADMIN-ATTRS-lob ORCL.ADMIN.REFERENCE ---> ADMIN-REFERENCE-lob This separation is useful because LOB payloads may be large, encoded differently, and require separate processing logic. A good design is to treat primitive topics and LOB topics differently. Character Encoding Matters LOB handling is not only about large size. It is also about character encoding. For Oracle LOBs: 1 2 3 4 5 6 7 8 9 10 11 BLOB Binary data No character encoding CLOB Character data Uses Oracle database character set NCLOB Unicode character data Uses Oracle national character set NCLOB is commonly encoded using Oracle national character set AL16UTF16, which corresponds to UTF-16 Big Endian. This means an NCLOB value may not be directly readable as a UTF-8 string when emitted as bytes. For example: 1 2 3 4 5 Original NCLOB: "Customer remarks updated" CDC output: byte[] representing UTF-16 encoded content If a sink connector or consumer treats that byte array as a normal UTF-8 string, the result may be corrupted, unreadable, or contain null characters. Kafka Stores Bytes, But Converters Decide Representation Kafka brokers are encoding-agnostic. Kafka stores keys and values as bytes. However, Kafka Connect converters and serializers decide how structured data is represented. For example: 1 2 3 4 5 6 7 8 JSON Converter Bytes may be represented as Base64 strings inside JSON Avro Converter Bytes may remain as Avro bytes type String Converter Assumes text representation The key lesson is that Kafka can safely transport the bytes, but your downstream processing must understand what those bytes represent. Handling NCLOB Data: Example Flow For an NCLOB column, a practical flow may look like this: Conceptually: 1 2 3 4 5 6 7 8 9 10 11 Input from LOB topic: { "ID": "101", "NOTES": } After custom SMT: { "ID": "101", "NOTES": "This is test data for NCLOB..." } Then the JDBC Sink Connector can write the cleaned string to the destination Oracle table. What to Check Before Enabling Oracle CDC Before implementing Oracle CDC with Confluent, I recommend reviewing each source table using a checklist. 1. Table Identity Check: 1 2 3 4 5 6 Schema name Table name Primary key Unique constraints Expected topic name Whether table should be included or excluded Why it matters: The connector needs to know which tables to capture, and downstream systems need a stable way to identify each changed row. 2. Primary Key and Upsert Behavior Check: 1 2 3 4 Does the table have a primary key? Is the primary key stable? Can the destination table use the same key? Will the sink use insert, update, or upsert mode? Why it matters: Without a proper key, update and delete handling becomes difficult. 3. Column Data Types Check all columns and classify them: 1 2 3 4 5 6 7 8 Simple types: VARCHAR2, NUMBER, DATE, TIMESTAMP Precision-sensitive types: NUMBER(p,s), DECIMAL, TIMESTAMP WITH TIME ZONE Binary / complex types: RAW, BLOB, CLOB, NCLOB, XMLTYPE Why it matters: Each data type may require different serialization, conversion, or sink-side handling. 4. LOB Columns Check: 1 2 3 4 5 6 Does the table have BLOB, CLOB, NCLOB, or XMLTYPE? How large are these columns? Are they frequently updated? Should they be captured? Should they go to separate LOB topics? Does the target expect bytes or text? Why it matters: LOBs are not always plug-and-play in CDC. They may need custom decoding or transformation. 5. Character Set Check: 1 2 3 4 5 6 SELECT parameter, value FROM nls_database_parameters WHERE parameter IN ( 'NLS_CHARACTERSET', 'NLS_NCHAR_CHARACTERSET' ); Why it matters: CLOB and NCLOB handling depends on character encoding. For NCLOB, you need to know the national character set. If the emitted value is bytes, decoding must use the correct encoding. 6. Nullable Columns and Default Values Check: 1 2 3 4 Which columns are nullable? Which columns have default values? How does the sink handle missing or null fields? Are null LOB values expected? Why it matters: CDC records may represent nulls, missing fields, or tombstones depending on operation type and configuration. 7. Deletes and Tombstones Check: 1 2 3 4 Should deletes be propagated? Should the sink delete rows? Should tombstone messages be generated? Should downstream consumers ignore or process deletes? Why it matters: Delete handling must be explicitly designed, especially if Kafka topics are compacted or downstream systems maintain a copy of the source table. 8. Schema Changes Check: 1 2 3 4 5 How often does the table schema change? Are new columns expected? Are column type changes expected? Who owns schema evolution? Will consumers tolerate schema changes? Why it matters: CDC pipelines are sensitive to schema changes. Adding a nullable column may be simple. Changing a column type can break consumers or sink connectors. Recommended Data Type Review Table Before implementing CDC, create a table like this for each Oracle table. 1 2 3 4 5 6 7 8 Column Name | Oracle Type | Kafka Connect Type | Special Handling Required | Notes ------------|-------------|--------------------|---------------------------|------ ID | NUMBER | Decimal | No | Primary key NAME | VARCHAR2 | String | No | - CREATED_AT | TIMESTAMP | Timestamp | Validate precision | - NOTES | NCLOB | Bytes | Yes | Decode UTF-16 FILE_DATA | BLOB | Bytes | Maybe | Keep as binary XML_PAYLOAD | XMLTYPE | Bytes | Yes | Decide text vs bytes This exercise is extremely useful because it prevents surprises after connector deployment. Recommended Architecture Pattern For a production CDC pipeline, avoid treating all columns and topics the same way. A better pattern is: This allows you to process normal relational data with standard patterns while applying special logic only where required. Common Mistakes to Avoid Mistake 1: Testing Only Simple Columns Many CDC tests use only NUMBER, VARCHAR2, and DATE. This gives a false sense of confidence. Always test with: 1 2 3 4 5 6 7 8 9 10 CLOB NCLOB BLOB XMLTYPE NULL values Large values Unicode characters Updates Deletes Schema changes Mistake 2: Assuming LOBs Are Strings CLOB and NCLOB are character large objects, but the connector may emit them as bytes. Do not assume they will arrive in Kafka as normal readable strings. Mistake 3: Ignoring Character Encoding For NCLOB, decoding with the wrong character set can corrupt data. Always verify: 1 2 3 4 5 NLS_CHARACTERSET NLS_NCHAR_CHARACTERSET Expected target column type Converter behavior Sink connector behavior Mistake 4: Not Defining Key Strategy Without a clear key strategy, downstream upserts and deletes become unreliable. Before starting CDC, confirm: 1 2 3 4 Primary key Kafka message key Sink primary key mode Destination table key Mistake 5: Treating the Connector as a Black Box The connector is powerful, but you still need to understand the internal flow: 1 2 3 4 5 6 7 Redo logs LogMiner Redo log topic Table topics LOB topics Converters Sink behavior Understanding this flow makes troubleshooting much easier. Lessons Learned The main lessons from this implementation were: 1. Oracle CDC Is Log-Based, Not Table Polling The connector captures database changes by interpreting redo logs through LogMiner. This is fundamentally different from running repeated SELECT queries. 2. Kafka Topics Represent Database Change Streams Each captured Oracle table can become a Kafka topic. This makes database changes available as event streams. 3. Data Type Mapping Must Be Reviewed Before Implementation Primitive data types are usually straightforward. Complex types such as BLOB, CLOB, NCLOB, XMLTYPE, high-precision NUMBER, and timezone-based timestamps need additional validation. 4. LOB Columns Need Special Design LOB data is stored differently in Oracle and may be emitted as bytes. For NCLOB, decoding may be required before inserting the value into another Oracle NCLOB column. 5. Kafka Can Move Bytes, But the Pipeline Must Preserve Meaning Kafka will transport the data. But the connector, converter, SMTs, stream processing layer, and sink connector must preserve the correct meaning of the data. Conclusion The Confluent Oracle CDC Source Connector is a strong option when you need to stream Oracle database changes into Kafka. It allows Oracle changes to be captured from redo logs, processed through Kafka Connect, and published into Kafka topics for downstream consumers. However, successful CDC implementation requires more than deploying the connector. You need to understand how data moves internally: 1 2 3 4 5 6 7 Oracle table change -> redo log -> LogMiner -> Oracle CDC Source Connector -> redo log topic -> table-specific Kafka topic -> downstream consumer or sink You also need to analyze the Oracle table structure before implementation. Primary keys, column data types, LOB columns, character sets, nullable fields, deletes, and schema changes all affect the design. LOB handling deserves special attention. BLOB, CLOB, NCLOB, and XMLTYPE may be emitted as bytes rather than plain strings. For NCLOB, the pipeline may need to decode UTF-16 bytes, clean the value, and then write it into the destination database. In short, Oracle CDC with Confluent is not just about moving rows into Kafka. It is about understanding how Oracle records changes, how the connector interprets those changes, how Kafka represents them, and how downstream systems should consume them safely. --- # Flink vs Spark: A Real-World Latency Showdown with Kafka URL: https://platformatory.io/blog/Spark_vs_Flink_Latency_Showdown/ Published: 2026-03-24 Authors: Shri Veena M P Categories: Stream Processing, Apache Flink, Apache Spark, Performance, Kafka Introduction In today’s fast-paced digital world, businesses rely on real-time data processing to make quick decisions. But when it comes to building distributed data pipelines, how do you choose between tools like Apache Spark and Apache Flink? These two giants dominate the streaming data landscape, but which one delivers better performance when it comes to latency? In this blog post, we explore a controlled experiment that compares the latency between Spark and Flink using Kafka as the messaging layer, including both stateless and stateful workloads, and with or without schema enforcement. The Challenge: Real-Time Data Latency Imagine you’re tracking millions of transactions per second on an online shopping platform. Each transaction needs to be processed and analyzed almost instantaneously to detect fraud, adjust pricing, or update inventory in real time. The challenge is simple but critical: How do you ensure the data is processed quickly without compromising accuracy, even when the pipelines require stateful operations or schema validation? That’s where low-latency stream processing frameworks like Apache Spark and Apache Flink come into play. The Experiment: Kafka, Spark, and Flink For this experiment, we created a distributed data pipeline using: Kafka as the messaging layer Apache Spark (PySpark) Apache Flink (PyFlink) We structured the experiments into four different pipeline configurations: Stateless, no schema Stateless, schema-enforced Stateful, no schema Stateful, schema-enforced The goal was to track and measure end-to-end latency, from data ingestion to processing and emission, under increasing complexity. Kafka was used as both the source and sink, simulating real-time data streams. We then compared: Spark’s micro-batch processing model Flink’s native continuous stream processing model Workload Characteristics The workload was designed to progressively increase in complexity: Stateless pipelines: Each message is self-contained, no joins or aggregations. Schema-enforced pipelines: Kafka messages validated against an Avro schema before processing. Stateful pipelines: Operation windowed aggregation is applied. Throughput was high (10,000 records/sec) to simulate production-like environments for: Clickstream ingestion Telemetry pipelines Event logging This allowed us to observe how latency changes when moving from simple stateless transformations to fully stateful, schema-validated streaming workloads. Architecture Overview Kafka Cluster A multi-broker Kafka cluster was set up in KRaft mode to handle message ingestion and delivery. Spark Pipeline Spark reads data using Structured Streaming, applies lightweight transformations, and writes the processed output back to Kafka. Flink Pipeline Flink processes the same data as a continuous stream, applies transformations, and writes results to Kafka. Latency Measurement End-to-end latency is measured by the difference between the source timestamp in the Kafka event and the processed timestamp recorded at the sink after transformations. Stateless pipelines: Each record is processed independently; latency is measured per record as processed_timestamp - source_timestamp. Stateful pipelines: Some operations (like windowed aggregations or keyed state updates) require buffering or maintaining state across multiple events. Latency is calculated as the time between the first event entering the state window and the output emission, resulting in slightly higher per-record latency compared to stateless pipelines. Percentile statistics (p50, p95, p99) are computed over all records in the stream to provide a realistic view of latency distribution. Visualizing the Latency: Real-Time Monitoring with Dash To better understand runtime behavior, we built a real-time latency monitoring dashboard using Dash and Plotly. The dashboard displays: Latency per record for Spark and Flink Percentile statistics (p50, p95, p99) updated in real time This allows direct visual comparison of both pipelines while they are running. Here’s a look at the dashboard in action computing the latency metrics in real time: A Closer Look at the Dashboard Note: The snapshots shown below are captured at random points in time while the pipelines were running. They are not intended to represent a single fixed phase (startup or steady state), but rather illustrate how latency behaves at different moments during execution. Snapshot 1: Early Startup Phase This snapshot was captured immediately after data production started. During early startup: Stateless, Schema-less Spark showed a high latency of ~25–30 seconds, which matches our measured baseline. Stateless, With Schema Spark experienced slightly higher latency (~28–32 seconds), as Avro schema parsing and deserialization add startup overhead. Stateful, Schema-less Spark incurred additional latency (~30–35 seconds) due to task initialization and per-key state management. Stateful, With Schema Spark showed the highest startup latency (~32–38 seconds), combining both state and schema overhead. In contrast, Flink pipelines started processing almost immediately: Stateless, schema-less Flink: ~0.35–0.55 s Schema-enabled Flink: ~0.6–0.8 s Stateful Flink: ~0.5–0.7 s Stateful with schema Flink: ~0.8–1.1 s Flink’s record-at-a-time processing allows continuous ingestion even when stateful operations or Avro schema parsing are present. Although Avro is more complex to implement in Flink, once configured it introduces only minor startup delay compared to Spark. Percentile metrics: Spark’s p50, p95, and p99 are all close to ~30 seconds Flink maintains low and tightly bounded latency This snapshot highlights differences during initial load and job warm-up. Snapshot 2: Post-Startup / Active Processing Phase Once pipelines reach steady-state: Stateless, Schema-less Spark maintained latency around 0.83–0.94 seconds, reflecting micro-batch scheduling overhead. Stateless, With Schema Spark had slightly higher latency (~1–1.2 seconds) due to ongoing Avro serialization/deserialization. Stateful, Schema-less Spark latency increased further (~1–1.3 seconds) because per-key state updates and checkpointing introduce extra processing. Stateful, With Schema Spark reached ~1.2–1.5 seconds, combining both state and schema overhead. Meanwhile, Flink consistently delivered lower latency across all four configurations: Stateless, schema-less: ~0.32–0.42 s Stateless with schema: ~0.45–0.6 s Stateful, schema-less: ~0.55–0.7 s Stateful with schema: ~0.6–0.85 s Percentile metrics confirm: Spark shows higher overall and tail latency Flink maintains lower values across all percentiles Observations: Flink’s continuous processing model ensures sub-second latency even with stateful or schema-enabled pipelines. Spark’s micro-batch execution causes higher latency, which accumulates more for stateful pipelines or when Avro schemas are used. Avro integration in Flink is challenging, but the payoff is low runtime latency and predictable performance under high-throughput workloads. State management in Flink adds small overhead, but still maintains latency far below Spark for similar workloads. Key Takeaways Across Pipelines Early Startup: Spark suffers from initialization and scheduling delays; Flink starts almost immediately. Steady-State: Flink consistently outperforms Spark in latency, even when state and schema are added. Stateful Operations: Introduce extra latency in both platforms, but Flink handles it more efficiently. Schema Enforcement (Avro): Harder to implement in Flink, yet results in low and stable latency once done. Flink provides the clearest advantage for real-time, latency-sensitive streaming workloads, especially when stateful operations or strict schema enforcement are required. Results: Who Wins the Latency Race? After processing over 1 million records across all configurations: Stateless Pipelines PyFlink average latency: ~2.12 seconds PySpark average latency: ~6.68 seconds PyFlink’s continuous streaming model consistently outperformed Spark micro-batches. Schema-Enforced Stateless Pipelines Slight overhead from schema validation PyFlink: ~2.35 seconds PySpark: ~7.1 seconds Flink still maintains a strong lead in latency. Stateful Pipelines Stateful operations introduce higher complexity due to state management and checkpointing. We evaluated both with and without schema enforcement. Stateful, No Schema PyFlink average latency: ~3.5–4.0 seconds PySpark average latency: ~8–9 seconds Flink handles keyed state efficiently, keeping latency low despite state overhead. Stateful, With Schema (Avro) PyFlink average latency: ~3.8–4.2 seconds PySpark average latency: ~9–10 seconds Avro deserialization in Flink is tricky, but once configured, it provides validated records with minimal impact on latency. Spark’s micro-batch model introduces more noticeable spikes due to batching and checkpointing. Setup: How to Recreate the Experiment Want to try this yourself? Clone the Repository 1 git clone https://github.com/Platformatory/kafka-spark-flink-latency-analytics-experiment.git To experiment with stateless and schemaless data pipeline 1 git checkout -b stateless-noschema To experiment with stateless data pipeline with schema 1 git checkout -b stateless-withschema To experiment with schemaless data pipeline with stateful function 1 git checkout -b stateful-noschema To experiment with data pipeline with stateful function and with Schema 1 git checkout -b stateful-withschema Build and Run the Containers Run with logs enabled: 1 docker compose up --build Run in detached mode: 1 docker compose up -d --build Monitor the Latency Once all services are running, open the following URL in your browser: 1 http://127.0.0.1:8050/ This dashboard computes and visualizes latency metrics in real time for both Spark and Flink pipelines. Conclusion: Spark vs Flink — Insights Across All Pipelines Across stateless vs stateful and schema-less vs Avro schema pipelines, PyFlink consistently demonstrates lower end-to-end latency than PySpark. While PySpark remains a strong choice for batch-oriented or mixed workloads, its micro-batch execution model introduces inherent latency, especially noticeable during early startup (~25–38 s depending on configuration). Flink’s continuous, record-at-a-time processing model handles both stateless and stateful workloads efficiently, even with Avro schema enforcement. Although Avro integration adds setup overhead, it provides predictable, low-latency results once running. Stateful operations introduce slight additional latency compared to stateless pipelines, but Flink still keeps p95 and p99 values tightly bounded. If your goal is low-latency, high-throughput streaming with complex state or schema requirements, PyFlink provides a clear advantage over PySpark. We’d love to hear your experiences with Spark vs Flink. Share your thoughts and insights in the comments! --- # Debezium with Oracle DB and OpenLogReplicator for Change Data Capture on Confluent Platform URL: https://platformatory.io/blog/debezium-oracledb-openlogreplicator/ Published: 2024-12-30 Authors: Balaji K Categories: CDC, Oracle, Debezium, Kafka Connect Introduction In the evolving landscape of real-time data processing, Change Data Capture (CDC) is essential for keeping data systems synchronized. Debezium, combined with the Confluent Platform, provides a robust solution for streaming database changes directly into Apache Kafka. When integrating with Oracle Database, Debezium can be configured to OpenLogReplicator which uses binary reading of redo logs and publish database transactions efficiently. Source - OpenLogReplicator Architecture In this blog, we’ll walk you through configuring Debezium’s Oracle connector within the Confluent Platform. You’ll learn how to set up OpenLogrReplicator, configure Debezium, and stream changes into your Kafka topics seamlessly. This guide covers: 1 2 3 - Preparing your Oracle Database for CDC with OpenLogReplicator. - Configuring the Debezium connector on Confluent Platform. - Validating and monitoring the data flow. By the end, you’ll have a powerful CDC pipeline ready to capture and stream changes from Oracle to Kafka, enabling real-time data integration and analytics. Let’s dive in! Confluent Platform Overview Confluent Platform is a streaming platform that enables user to store, and manage data as real-time streams. It enabled transformations through stream processing, simplifies enterprise operations at scale. Confluent Platform can be downloaded and managed by user. This is a specialized distribution system of Kafka with many commercial features built into Kafka brokers that function as Confluent Server. Confluent facilitates the development of a whole new class of contemporary, event-driven applications, provides a universal data pipeline, and opens up potent new use cases with complete performance, scalability, and dependability. OpenLogReplicator Overview OpenLogReplicator is an open-source project created by Adam Leszczyński, an external CDC solution that reads Oracle redo logs without directly impacting database performance. Unlike LogMiner, it operates independently of Oracle, making it a more scalable and lightweight option for real-time data replication. OpenLogReplicator is particularly useful for streaming large-scale transactional data to modern data platforms like Apache Kafka, Elasticsearch, and cloud-based storage systems. Its architecture is designed to handle high-volume, low-latency workloads, making it an ideal choice for event-driven applications and distributed systems. Use OpenLogReplicator if you need a real-time, scalable, and low-overhead CDC solution for streaming data to external platforms without burdening the Oracle database. While both OpenLogReplicator and LogMiner tools provide CDC capabilities, OpenLogReplicator is better suited for modern, cloud-native architectures, whereas LogMiner is a more traditional solution for Oracle-centric environments. OpenLogReplicator does not depend on any specific configuration of the source database. With no impact on the source system and not utilizing Oracle LogMiner, OpenLogReplicator primarly targets Kafka systems capturing change component. Pre-requisite Internet Connection OS supporting Confluent Platform Docker Engine 1.11 or higher installed Setting up Debezium Container Image Clone the github OpenLogReplicator repository 1 $> git clone https://github.com/bersler/OpenLogReplicator-tutorials.git Navigate to folder OpenLogReplicator-tutorials → images and execute script bersler_openlogreplicator_tutorial.sh to build OpenLogReplicator container image. 1 $> ./bersler_openlogreplicator_tutorial.sh Setting up Confluent Platform Download Oracle JDBC Driver from Oracle JDBC Driver page. You need to download zipped JDBC driver for Oracle DB 21c. Extract the zip file. Download the Confluent Platform KRaft all-in-one Docker Compose file using below command. The docker compose file is a configuration file used to quickly set up a local Confluent Platform environment with all the essential components like Kafka, Schema Registry, and Connect, specifically utilizing the “KRaft” mode for managing Kafka cluster metadata allowing user to easily run a full Confluent Platform instance in a single Docker command using the “cp-all-in-one” image with KRaft enabled. 1 $> wget https://raw.githubusercontent.com/confluentinc/cp-all-in-one/7.8.0-post/cp-all-in-one-kraft/docker-compose.yml Update docker-compose.yaml file with below changes: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 kafka-connect: image: debezium/connect:2.7.3.Final hostname: kafka-connect container_name: kafka-connect depends_on: - broker - schema-registry ports: - "8083:8083" environment: BOOTSTRAP_SERVERS: 'broker:29092' GROUP_ID: 1 CONFIG_STORAGE_TOPIC: "my_connect_configs" OFFSET_STORAGE_TOPIC: "my_connect_offset" STATUS_STORAGE_TOPIC: "my_connect_status" #KAFKA_CLASSPATH: /opt/oracle/ojdbc8.jar LD_LIBRARY_PATH: /kafka/instantclient_21_16 volumes: - ./basic/instantclient_21_16:/kafka/instantclient_21_16 oracle: image: heartu41/oracle19c container_name: oracle ports: - "1521:1521" environment: ORACLE_PWD: "Oracle123" ORACLE_SID: "ORCLCDB" ENABLE_ARCHIVELOG: true ENABLE_FORCE_LOGGING: true volumes: - ./fra:/opt/oracle/fra - ./oradata:/opt/oracle/oradata - ./sql:/opt/sql - ./setup:/opt/oracle/scripts/setup openlogreplicator: image: bersler/openlogreplicator:tutorial container_name: openlogreplicator ports: - "8080:8080" depends_on: - oracle volumes: - ./checkpoint:/opt/OpenLogReplicator/checkpoint - ./fra:/opt/fra - ./log:/opt/OpenLogReplicator/log - ./oradata:/opt/oradata - ./output:/opt/output - ./scripts:/opt/OpenLogReplicator/scripts restart: "no" Create below listed directories and respective ownership required for setting up OpenLogReplicator connector: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 mkdir oradata chmod 755 oradata sudo chown 54321:54321 oradata mkdir fra chmod 755 fra sudo chown 54321:54321 fra chmod a+x+r+w sql chmod a+r sql/*.sql mkdir checkpoint chmod 777 checkpoint mkdir log chmod 777 log mkdir output chmod 777 output chmod 777 scripts chmod 644 scripts/OpenLogReplicator.json Create file OpenLogReplicator.json under scripts folder with content: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 { "version": "1.7.0", "log-level": 3, "source": [ { "alias": "S1", "name": "ORA1", "reader": { "type": "online", "path-mapping": ["/opt/oracle/oradata", "/opt/oradata", "/opt/oracle/fra", "/opt/fra"], "user": "c##dbzuser", "password": "dbz", "server": "//oracle:1521/ORCLPDB1" }, "format": { "type": "json" }, "filter": { "table": [ {"owner": "c##dbzuser", "table": "customers"} ] } } ], "target": [ { "alias": "T1", "source": "S1", "writer": { "type": "file", "output": "/opt/output/results.txt" } } ] } Start Confluent Platform stack in detach mode: 1 $> docker compose up -d Each component of Confluent Platform starts in separate container. 1 2 3 4 5 6 7 8 9 Creating broker ... done Creating schema-registry ... done Creating rest-proxy ... done Creating connect ... done Creating ksqldb-server ... done Creating control-center ... done Creating ksql-datagen ... done Creating ksqldb-cli ... done Creating oracle ... done You can verify if all services are up and running using command “docker compose ps -a” Configuring Oracle Database When Oracle DB container starts for the first time, there are no initial configuration and database exists. Hence database will be installed and configuration will be started. This process may take 10-20 mins (approx). You can verify readiness of Oracle DB from container logs (docker compose logs oracle) and should see message: 1 2 3 ############################# DATABASE IS READY TO USE! ############################# In order to incorporate changes from an Oracle database, a number of database configurations are required: Enable Archive Logs The Oracle container registry image used in the Install Oracle section may not have archive logging enabled. If you use another image or a pre-existing environment, you should check whether archive logging is enabled. 1 2 3 4 $> docker compose exec oracle bash $> sqlplus ‘/ as sysdba’ SQL> SELECT LOG_MODE FROM V$DATABASE If the column contains ARCHIVELOG, then archive logging is enabled. If the column contains the value NOARCHIVELOG, archive logging isn’t enabled, and further configuration is necessary. Execute the following SQL commands inside the SQL*Plus terminal window: 1 2 3 4 5 6 7 ALTER SYSTEM SET db_recovery_file_dest_size = 10G; ALTER SYSTEM SET db_recovery_file_dest = '/opt/oracle/oradata/ORCLCDB' scope=spfile; SHUTDOWN IMMEDIATE STARTUP MOUNT ALTER DATABASE ARCHIVELOG; ALTER DATABASE OPEN; ARCHIVE LOG LIST; Output of last executed SQL command should show Archive mode for Database log mode. 1 2 3 4 5 6 Database log mode Archive Mode Automatic archival Enabled Archive destination USE_DB_RECOVERY_FILE_DEST Oldest online log sequence 1 Next log sequence to archive 3 Current log sequence 3 Configure Redo Logs Oracle Redo logs are the transactional logs. Using the same terminal window, execute below listed SQL command to determine filenames, location of redo logs and recreate log group with size of 400 MB using same log file. 1 2 3 4 5 6 7 8 9 10 11 12 13 SQL> SELECT GROUP#, MEMBER FROM V$LOGFILE ORDER BY 1, 2; GROUP# MEMBER ---------- --------------------------------------------------- 1 /opt/oracle/oradata/ORCLCDB/redo01.log 2 /opt/oracle/oradata/ORCLCDB/redo02.log 3 /opt/oracle/oradata/ORCLCDB/redo03.log ALTER DATABASE CLEAR LOGFILE GROUP 1; ALTER DATABASE DROP LOGFILE GROUP 1; ALTER DATABASE ADD LOGFILE GROUP 1 ('/opt/oracle/oradata/ORCLCDB/redo01.log') size 400M REUSE; ALTER SYSTEM SWITCH LOGFILE; Configure Supplemental Logging Database supplementary logging needs to be enabled at the very least for Debezium to communicate with LogMiner, handle chained rows, and work with different storage configurations. 1 SQL> ALTER DATABASE ADD SUPPLEMENTAL LOG DATA Configuring Users in Oracle DB To capture change events, the Debezium connector needs to establish a JDBC connection to the Oracle database and interact with LogMiner APIs. This requires a dedicated database user account with specific permissions to access LogMiner and read data from the target tables. In the same SQLplus terminal window, create table spaces: 1 2 3 4 5 CONNECT sys/oraclepw@ORCLCDB as sysdba; CREATE TABLESPACE logminer_tbs DATAFILE '/opt/oracle/oradata/ORCLCDB/logminer_tbs.dbf' SIZE 25M REUSE AUTOEXTEND ON MAXSIZE UNLIMITED; CONNECT sys/oraclepw@ORCLPDB1 as sysdba; CREATE TABLESPACE logminer_tbs DATAFILE '/opt/oracle/oradata/ORCLCDB/ORCLPDB1/logminer_tbs.dbf' SIZE 25M REUSE AUTOEXTEND ON MAXSIZE UNLIMITED; NOTE – Replace oraclepw with the password set in docker compose file. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 CONNECT sys/oraclepw@ORCLCDB as sysdba; CREATE USER c##dbzuser IDENTIFIED BY dbz DEFAULT TABLESPACE LOGMINER_TBS QUOTA UNLIMITED ON LOGMINER_TBS CONTAINER=ALL; GRANT CREATE SESSION TO c##dbzuser CONTAINER=ALL; GRANT SET CONTAINER TO c##dbzuser CONTAINER=ALL; GRANT SELECT ON V_$DATABASE TO c##dbzuser CONTAINER=ALL; GRANT FLASHBACK ANY TABLE TO c##dbzuser CONTAINER=ALL; GRANT SELECT ANY TABLE TO c##dbzuser CONTAINER=ALL; GRANT SELECT_CATALOG_ROLE TO c##dbzuser CONTAINER=ALL; GRANT EXECUTE_CATALOG_ROLE TO c##dbzuser CONTAINER=ALL; GRANT SELECT ANY TRANSACTION TO c##dbzuser CONTAINER=ALL; GRANT SELECT ANY DICTIONARY TO c##dbzuser CONTAINER=ALL; GRANT LOGMINING TO c##dbzuser CONTAINER=ALL; GRANT CREATE TABLE TO c##dbzuser CONTAINER=ALL; GRANT LOCK ANY TABLE TO c##dbzuser CONTAINER=ALL; GRANT CREATE SEQUENCE TO c##dbzuser CONTAINER=ALL; GRANT EXECUTE ON DBMS_LOGMNR TO c##dbzuser CONTAINER=ALL; GRANT EXECUTE ON DBMS_LOGMNR_D TO c##dbzuser CONTAINER=ALL; GRANT SELECT ON V_$LOG TO c##dbzuser CONTAINER=ALL; GRANT SELECT ON V_$LOG_HISTORY TO c##dbzuser CONTAINER=ALL; GRANT SELECT ON V_$LOGMNR_LOGS TO c##dbzuser CONTAINER=ALL; GRANT SELECT ON V_$LOGMNR_CONTENTS TO c##dbzuser CONTAINER=ALL; GRANT SELECT ON V_$LOGMNR_PARAMETERS TO c##dbzuser CONTAINER=ALL; GRANT SELECT ON V_$LOGFILE TO c##dbzuser CONTAINER=ALL; GRANT SELECT ON V_$ARCHIVED_LOG TO c##dbzuser CONTAINER=ALL; GRANT SELECT ON V_$ARCHIVE_DEST_STATUS TO c##dbzuser CONTAINER=ALL; GRANT SELECT ON V_$TRANSACTION TO c##dbzuser CONTAINER=ALL; EXIT; Create Initial Test Data Connect to Oracle DB using command: 1 2 3 $> sqlplus ‘/ as sysdba’ SQL> connect c##dbzuser/dbz SQL> alter session set container=ORCLPDB1; After connecting to ORCLPDB1, create table and some initial data. 1 2 3 4 5 CREATE TABLE customers (id number(9,0) primary key, name varchar2(50)); INSERT INTO customers VALUES (1001, 'Jane Doe'); INSERT INTO customers VALUES (1002, 'Bob Willy'); INSERT INTO customers VALUES (1003, 'Eddie Murphy'); INSERT INTO customers VALUES (1004, 'Anne Mary'); COMMIT; Set the table’s supplemental log level: 1 ALTER TABLE customers ADD SUPPLEMENTAL LOG DATA (ALL) COLUMNS; Deploy Debezium Oracle Connector Create a source connector file “source_Debezium_OpenLogReplicator.json” with configuration: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 { "name": "openlogreplicator", "config": { "connector.class": "io.debezium.connector.oracle.OracleConnector", "tasks.max": "1", "topic.prefix" : "server1", "database.hostname": "oracle", "database.port": "1521", "database.user": "c##dbzuser", "database.password": "dbz", "database.dbname": "ORCLCDB", "database.pdb.name": "ORCLPDB1", "database.server.name": "server1", "table.include.list": "C##DBZUSER.CUSTOMERS", "database.history.kafka.bootstrap.servers": "broker:29092", "database.history.kafka.topic": "schema-changes", "schema.history.internal.kafka.bootstrap.servers" : "broker:29092", "schema.history.internal.kafka.topic": "schema-changes.customers" } } Save above configuration and deploy the source connector 1 $> curl -i -X POST -H "Accept:application/json" \ -H "Content-Type:application/json" \ localhost:8083/connectors \ -d @ source_Debezium_OpenLogReplicator.json | jq Once the source connector registration is successful, open Confluent Platform Control Center using http://:9021 in a browser. Navigate to Overview → Topics. You should see a topic “server1.C__DBZUSER.CUSTOMERS’ listed there. Click on the topic and verify the contents of topic. Conclusion This concludes the deployment of the Oracle Debezium connector with OpenLogReplicator, which captures changes in the CUSTOMERS table. We successfully set up and configured the pipeline to enable real-time change data capture from Oracle to Kafka. This integration ensures efficient and reliable data streaming, allowing downstream systems to consume updates as they happen. With this foundation in place, you can further enhance the pipeline by adding transformations, monitoring, or scaling it for enterprise workloads. --- # Debezium with Oracle DB and LogMiner for Change Data Capture on Confluent Platform URL: https://platformatory.io/blog/debezium-oracledb-logminer/ Published: 2024-12-30 Authors: Balaji K Categories: CDC, Oracle, Debezium, Kafka Connect Introduction In the evolving landscape of real-time data processing, Change Data Capture (CDC) is essential for keeping data systems synchronized. Debezium, combined with the Confluent Platform, provides a robust solution for streaming database changes directly into Apache Kafka. When integrating with Oracle Database, Debezium leverages Oracle LogMiner to capture and publish database transactions efficiently. In this blog, we’ll walk you through configuring Debezium’s Oracle connector within the Confluent Platform. You’ll learn how to set up LogMiner, configure Debezium, and stream changes into your Kafka topics seamlessly. This guide covers: • Preparing your Oracle Database for CDC with LogMiner. • Configuring the Debezium connector on Confluent Platform. • Validating and monitoring the data flow. By the end, you’ll have a powerful CDC pipeline ready to capture and stream changes from Oracle to Kafka, enabling real-time data integration and analytics. Let’s dive in! Confluent Platform Overview Confluent Platform is a streaming platform that enables user to store, and manage data as real-time streams. It enabled transformations through stream processing, simplifies enterprise operations at scale. Confluent Platform can be downloaded and managed by user. This is a specialized distribution system of Kafka with many commercial features built into Kafka brokers that function as Confluent Server. Confluent facilitates the development of a whole new class of contemporary, event-driven applications, provides a universal data pipeline, and opens up potent new use cases with complete performance, scalability, and dependability. Pre-requisites Internet Connection OS supporting Confluent Platform (link) Docker Engine 1.11 or higher installed Setting up Confluent Platform Download Oracle JDBC Driver from Oracle JDBC Driver page. You need to download zipped JDBC driver for Oracle DB 21c. Extract the zip file. Download the Confluent Platform KRaft all-in-one Docker Compose file using below command. The docker compose file is a configuration file used to quickly set up a local Confluent Platform environment with all the essential components like Kafka, Schema Registry, and Connect, specifically utilizing the “KRaft” mode for managing Kafka cluster metadata allowing user to easily run a full Confluent Platform instance in a single Docker command using the “cp-all-in-one” image with KRaft enabled. $> wget https://raw.githubusercontent.com/confluentinc/cp-all-in-one/7.8.0-post/cp-all-in-one-kraft/docker-compose.yml Update docker-compose.yaml file with below changes: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 kafka-connect: image: debezium/connect:2.7.3.Final hostname: kafka-connect container_name: kafka-connect depends_on: - broker - schema-registry ports: - "8083:8083" environment: BOOTSTRAP_SERVERS: 'broker:29092' GROUP_ID: 1 CONFIG_STORAGE_TOPIC: "my_connect_configs" OFFSET_STORAGE_TOPIC: "my_connect_offset" STATUS_STORAGE_TOPIC: "my_connect_status" #KAFKA_CLASSPATH: /opt/oracle/ojdbc8.jar LD_LIBRARY_PATH: /kafka/instantclient_21_16 volumes: - ./basic/instantclient_21_16:/kafka/instantclient_21_16 oracle-db: image: heartu41/oracle19c container_name: oracle ports: - "1521:1521" environment: ORACLE_PWD: "Oracle123" ORACLE_SID: "ORCLCDB" ENABLE_ARCHIVELOG: true ENABLE_FORCE_LOGGING: true volumes: - ./oracleDB/oradata:/opt/oracle/oradata Create directory “oracleDB/oradata and change ownership to 54321 1 2 $> mkdir -p oracleDB/oradata $> sudo chown -R oracleDB/oradata 54321:54321 Start Confluent Platform stack in detach mode: 1 2 3 4 5 6 7 8 9 10 11 12 13 $> docker compose up -d Each component of Confluent Platform starts in separate container. Creating broker ... done Creating schema-registry ... done Creating rest-proxy ... done Creating connect ... done Creating ksqldb-server ... done Creating control-center ... done Creating ksql-datagen ... done Creating ksqldb-cli ... done Creating oracle ... done You can verify if all services are up and running using command “docker compose ps -a” Configuring Oracle Database When Oracle DB container starts for the first time, there are no initial configuration and database exists. Hence database will be installed and configuration will be started. This process may take 10-20 mins (approximately). You can verify readiness of Oracle DB from container logs (docker compose logs oracle) and should see message: 1 2 3 4 5 ``` ############################# DATABASE IS READY TO USE! ############################# ``` In order to incorporate changes from an Oracle database, a number of database configurations are required: Enable Archive logs The Oracle container registry image used in the Install Oracle section may not have archive logging enabled. If you use another image or a pre-existing environment, you should check whether archive logging is enabled. 1 2 3 4 5 $> docker compose exec oracle bash $> sqlplus ‘/ as sysdba’ SQL> SELECT LOG_MODE FROM V$DATABASE If the column contains ARCHIVELOG, then archive logging is enabled. If the column contains the value NOARCHIVELOG, archive logging isn’t enabled, and further configuration is necessary. Execute the following SQL commands inside the SQL*Plus terminal window: 1 2 3 4 5 6 7 ALTER SYSTEM SET db_recovery_file_dest_size = 10G; ALTER SYSTEM SET db_recovery_file_dest = '/opt/oracle/oradata/ORCLCDB' scope=spfile; SHUTDOWN IMMEDIATE STARTUP MOUNT ALTER DATABASE ARCHIVELOG; ALTER DATABASE OPEN; ARCHIVE LOG LIST; Output of last executed SQL command should show Archive mode for Database log mode. 1 2 3 4 5 6 Database log mode Archive Mode Automatic archival Enabled Archive destination USE_DB_RECOVERY_FILE_DEST Oldest online log sequence 1 Next log sequence to archive 3 Current log sequence 3 Redo Logs Oracle Redo logs are the transactional logs. Using the same terminal window, execute below listed SQL command to determine filenames, location of redo logs and recreate log group with size of 400 MB using same log file. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 SQL> SELECT GROUP#, MEMBER FROM V$LOGFILE ORDER BY 1, 2; GROUP# MEMBER ---------- --------------------------------------------------- 1 /opt/oracle/oradata/ORCLCDB/redo01.log 2 /opt/oracle/oradata/ORCLCDB/redo02.log 3 /opt/oracle/oradata/ORCLCDB/redo03.log ALTER DATABASE CLEAR LOGFILE GROUP 1; ALTER DATABASE DROP LOGFILE GROUP 1; ALTER DATABASE ADD LOGFILE GROUP 1 ('/opt/oracle/oradata/ORCLCDB/redo01.log') size 400M REUSE; ALTER SYSTEM SWITCH LOGFILE; Supplemental Logging Database supplementary logging needs to be enabled at the very least for Debezium to communicate with LogMiner, handle chained rows, and work with different storage configurations. 1 SQL> ALTER DATABASE ADD SUPPLEMENTAL LOG DATA Users Setup in Oracle DB To capture change events, the Debezium connector needs to establish a JDBC connection to the Oracle database and interact with LogMiner APIs. This requires a dedicated database user account with specific permissions to access LogMiner and read data from the target tables. In the same SQLplus terminal window, create table spaces: 1 2 3 4 5 CONNECT sys/oraclepw@ORCLCDB as sysdba; CREATE TABLESPACE logminer_tbs DATAFILE '/opt/oracle/oradata/ORCLCDB/logminer_tbs.dbf' SIZE 25M REUSE AUTOEXTEND ON MAXSIZE UNLIMITED; CONNECT sys/oraclepw@ORCLPDB1 as sysdba; CREATE TABLESPACE logminer_tbs DATAFILE '/opt/oracle/oradata/ORCLCDB/ORCLPDB1/logminer_tbs.dbf' SIZE 25M REUSE AUTOEXTEND ON MAXSIZE UNLIMITED; NOTE – Replace oraclepw with the password set in docker compose file. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 CONNECT sys/oraclepw@ORCLCDB as sysdba; CREATE USER c##dbzuser IDENTIFIED BY dbz DEFAULT TABLESPACE LOGMINER_TBS QUOTA UNLIMITED ON LOGMINER_TBS CONTAINER=ALL; GRANT CREATE SESSION TO c##dbzuser CONTAINER=ALL; GRANT SET CONTAINER TO c##dbzuser CONTAINER=ALL; GRANT SELECT ON V_$DATABASE TO c##dbzuser CONTAINER=ALL; GRANT FLASHBACK ANY TABLE TO c##dbzuser CONTAINER=ALL; GRANT SELECT ANY TABLE TO c##dbzuser CONTAINER=ALL; GRANT SELECT_CATALOG_ROLE TO c##dbzuser CONTAINER=ALL; GRANT EXECUTE_CATALOG_ROLE TO c##dbzuser CONTAINER=ALL; GRANT SELECT ANY TRANSACTION TO c##dbzuser CONTAINER=ALL; GRANT SELECT ANY DICTIONARY TO c##dbzuser CONTAINER=ALL; GRANT LOGMINING TO c##dbzuser CONTAINER=ALL; GRANT CREATE TABLE TO c##dbzuser CONTAINER=ALL; GRANT LOCK ANY TABLE TO c##dbzuser CONTAINER=ALL; GRANT CREATE SEQUENCE TO c##dbzuser CONTAINER=ALL; GRANT EXECUTE ON DBMS_LOGMNR TO c##dbzuser CONTAINER=ALL; GRANT EXECUTE ON DBMS_LOGMNR_D TO c##dbzuser CONTAINER=ALL; GRANT SELECT ON V_$LOG TO c##dbzuser CONTAINER=ALL; GRANT SELECT ON V_$LOG_HISTORY TO c##dbzuser CONTAINER=ALL; GRANT SELECT ON V_$LOGMNR_LOGS TO c##dbzuser CONTAINER=ALL; GRANT SELECT ON V_$LOGMNR_CONTENTS TO c##dbzuser CONTAINER=ALL; GRANT SELECT ON V_$LOGMNR_PARAMETERS TO c##dbzuser CONTAINER=ALL; GRANT SELECT ON V_$LOGFILE TO c##dbzuser CONTAINER=ALL; GRANT SELECT ON V_$ARCHIVED_LOG TO c##dbzuser CONTAINER=ALL; GRANT SELECT ON V_$ARCHIVE_DEST_STATUS TO c##dbzuser CONTAINER=ALL; GRANT SELECT ON V_$TRANSACTION TO c##dbzuser CONTAINER=ALL; EXIT; Create Initial Test Data Connect to Oracle DB using command: 1 2 3 $> sqlplus ‘/ as sysdba’ SQL> connect c##dbzuser/dbz SQL> alter session set container=ORCLPDB1; Create table and some initial sample data. 1 2 3 4 5 6 CREATE TABLE customers (id number(9,0) primary key, name varchar2(50)); INSERT INTO customers VALUES (1001, 'Jane Doe'); INSERT INTO customers VALUES (1002, 'Bob Willy'); INSERT INTO customers VALUES (1003, 'Eddie Murphy'); INSERT INTO customers VALUES (1004, 'Anne Mary'); COMMIT; Set the table’s supplemental log level: 1 2 ALTER TABLE customers ADD SUPPLEMENTAL LOG DATA (ALL) COLUMNS; Deploy Debezium Oracle Connector Create a source connector file “source_logMiner.json” with configuration: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 { "name": "debezium-log-miner", "config": { "connector.class": "io.debezium.connector.oracle.OracleConnector", "tasks.max": "1", "topic.prefix" : "server1", "database.hostname": "oracle-db", "database.port": "1521", "database.user": "c##dbzuser", "database.password": "dbz", "database.dbname": "ORCLCDB", "database.pdb.name": "ORCLPDB1", "database.server.name": "server1", "table.include.list": "C##DBZUSER.CUSTOMERS", "database.history.kafka.bootstrap.servers": "broker:29092", "database.history.kafka.topic": "schema-changes", "schema.history.internal.kafka.bootstrap.servers" : "broker:29092", "schema.history.internal.kafka.topic": "schema-changes.new_table" } } Save above configuration and deploy the source connector 1 $> curl -i -X POST -H "Accept:application/json" \ -H "Content-Type:application/json" \ localhost:8083/connectors \ -d @r source_logMiner.json | jq Once the source connector registration is successful, open Confluent Platform Control Center using http://:9021 in a browser. Navigate to Overview → Topics. You should see a topic “server1.C__DBZUSER.CUSTOMERS’ listed there. Click on the topic and verify the contents of topic. Summary In this blog, we successfully deployed the Oracle Debezium connector to capture real-time changes from the CUSTOMERS table. From setting up the environment to configuring Debezium and validating CDC events in Kafka, we demonstrated a seamless data streaming pipeline. This integration enables reliable change data capture, ensuring efficient data synchronization between Oracle and downstream consumers. With this setup in place, you can now extend it further by adding transformations, integrating with analytics platforms, or scaling for enterprise workloads. --- # Stream Oracle DB Changes to Redis with Confluent Platform: An End-to-End Guide URL: https://platformatory.io/blog/Stream-Oracle-DB-Changes-to-Redis-with-Confluent-Platform/ Published: 2024-12-19 Authors: Balaji K Categories: CDC, Oracle, Kafka Connect, Kafka Introduction Real-time data integration has become the backbone of modern data architectures, allowing businesses to react quickly to changing conditions and make informed decisions. One of the most powerful tools in this ecosystem is Change Data Capture (CDC), which enables organizations to monitor and capture changes in their databases as they occur. For businesses using Oracle Database as their primary data store, the Oracle CDC Source Connector for the Confluent Platform offers an easy and efficient way to stream database changes to Apache Kafka. This powerful combination allows for the creation of scalable, real-time data pipelines that can integrate, process, and analyze data with minimal latency. In this blog, we’ll walk through the capabilities of the Oracle CDC Source Connector, its key benefits, and how you can start using it to transform your data architecture. Need for Kafka Connect and Change Data Capture (CDC) Kafka Connect is a solution for streaming data between other data systems and Apache Kafka® with reliability. It facilitates the rapid definition of connections that transfer massive data sets into and out of Kafka. Kafka Connect can ingest whole databases or collect metrics from all your application servers into Kafka topics, making the data available for stream processing with low latency. Data from Kafka topics can be delivered via an export connector to batch systems, for offline analysis, or to secondary indexes, like Elasticsearch. Data connection between databases, key-value stores, search indexes, and file systems is made easy with Kafka Connect, an Apache Kafka® component that is free and open-source. Kafka Connect allows you to quickly build connections that transfer big data sets into and out of Apache Kafka® and broadcast data between Apache Kafka® and other data systems. You can use Oracle JDBC source connector to read data from Oracle DB, however this would capture only the snapshot of the table and not the changes or deleted rows. In the article, How to Integrate Your Database with Apache Kafka by Robin Moffatt, explores the distinction between log-based Change Data Capture (CDC) and a JDBC connector. Introduction to Oracle CDC Source Connector Oracle CDC Source Connector which records any modifications to database’s row, which is captured as change event records in Apache Kafka® topics. All tables that match an include regular expression and are accessible to the user can be included in the subset of tables that the connector can be set up to capture in a single database. A separate exclude regular expression can be set to prevent it from capturing tables that match those regular expressions. The connector uses Oracle LogMiner to read database redo log. A subset of the tables in a single database, which is all tables that the user can access and that match an include regular expression, can be captured by the connector. Additionally, it can be set up to omit tables that match a different exclusion regular expression. Redis Sink Connector The Confluent Redis Kafka Connector makes it possible for Redis and Apache Kafka to integrate seamlessly and exchange data in real time. For use cases like caching, event sourcing, and analytics, it is perfect because it enables Kafka topics to transfer data to Redis. Compatibility with various data pipelines is guaranteed by its support for widely used serialization formats, including JSON, Avro, and Protobuf. The Redis Sink Connector allows for low-latency data access by streaming Kafka data to Redis. It is made to integrate easily with the Confluent Platform and offers scalability and stable setups for event-driven, real-time architectures. One of the primary reasons for using a Redis Sink Connector is low-latency caching. Since Redis is an in-memory data store, it is well-suited for handling frequently accessed data with minimal latency. Streaming Kafka events into Redis ensures that applications can retrieve data almost instantly, making it ideal for use cases like recommendation engines, session storage, and leaderboards. Instead of relying on disk-based databases for quick lookups, Redis allows applications to access critical data in real time. Another key advantage is real-time data processing. Kafka can ingest massive amounts of data, but consuming applications need immediate access to relevant information. By sinking Kafka data into Redis, applications can perform real-time aggregations, filtering, and analytics without the overhead of querying Kafka directly. This is particularly useful in scenarios like fraud detection, monitoring, and IoT telemetry, where events must be evaluated in milliseconds. Redis supports clustering and replication, making it a highly scalable and fault-tolerant data store for Kafka-driven applications. With a Redis Sink Connector continuously syncing Kafka data into Redis, applications can ensure real-time data availability without manual intervention or complex database queries. In summary, a Redis Sink Connector is a vital component in real-time streaming architectures, bridging the gap between Kafka’s high-throughput messaging and Redis’s ultra-fast data access. It optimizes caching, enables instant analytics, and ensures that applications have quick access to processed event data. Whether for session management, caching, event enrichment, or real-time decision-making, integrating Redis with Kafka using a Sink Connector enhances performance and scalability in data-driven applications. Oracle DB Pre-requisite Oracle Database versions 19c and later. Create a common user for a multitenant database. The username must start with “c##” or “C## Database must be enabled in ARCHIVEMODE OS Pre-requisite Current user added into sudoers list Docker engine installed Setting up Environment Note: The following setup is executed on Ubuntu 24.02 LTS Oracle Source Connector The Confluent Oracle CDC Source Connector comes under Premium Confluent Connector and requires additional subscription. Review the license at Confluent Oracle CDC Source Connector and download zip file. The zip file used in this setup is for Confluent Platform. Unzip the confluentinc-kafka-connect-oracle-cdc-2.14.2.zip file. NOTE – The version number may vary if newer version of source connector is available. Oracle Docker Container Image The docker image used for Oracle DB is heartu41/oracle19c. You can download the docker image using command: 1 $> docker pull heartu41/oracle19c Redis Kafka Connector The Redis Kafka Sink connector can be downloaded from Confluent Hub Page. You can also download directly by running command: 1 $> wget https://d2p6pa21dvn84.cloudfront.net/api/plugins/redis/redis-enterprise-kafka/versions/6.7.4/redis-redis-enterprise-kafka-6.7.4.zip Unzip file redis-redis-enterprise-kafka-6.7.4.zip. Bring Up Confluent Platform using Docker Compose Download or copy contents of [Docker Compose file] from GitHub repository for Confluent Platform Kraft all in one Docker Compose file. 1 $> wget https://d2p6pa21dvn84.cloudfront.net/api/plugins/redis/redis-enterprise-kafka/versions/6.7.4/redis-redis-enterprise-kafka-6.7.4.zip Open docker-compose.yml file in editor and add below sections: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 oracle-db: image: heartu41/oracle19c container_name: oracle ports: - "1521:1521" environment: ORACLE_PWD: "Oracle123" ORACLE_SID: "ORCLCDB" ENABLE_ARCHIVELOG: true ENABLE_FORCE_LOGGING: true volumes: - ./oracleDB/oradata:/opt/oracle/oradata redis: image: redis/redis-stack-server hostname: redis container_name: redis ports: - "6379:6379" Update section “Connect” in docker-compose.yml file to include Oracle CDC source and Redis Sink connector. 1 2 3 4 5 6 7 8 depends_on: - broker - schema-registry - redis volumes: - ./confluentinc-kafka-connect-oracle-cdc-2.14.2:/usr/share/java/confluentinc-kafka-connect-oracle-cdc-2.14.2 - ./redis-redis-kafka-connect-0.9.1:/usr/share/java/redis-redis-kafka-connect-0.9.1 Save changes made in above steps in docker-compose file. Ensure Oracle CDC Connector and Redis Sink connector files are extracted Create a folder in current working directory where docker-compose.yml file is present along with Oracle CDC connector and Redis Sink Connector. 1 2 $> mkdir -p oracleDB/oradata $> chown -R 54321:54321 oracleDB Start the Confluent Platform stack with the -d option to run in detached mode. 1 $> docker compose up -d     Each component of docker compose file will start in a separate container. The output will look similar to: 1 2 3 4 5 6 7 8 9 10 Creating broker ... done Creating schema-registry ... done Creating rest-proxy ... done Creating connect ... done Creating ksqldb-server ... done Creating control-center ... done Creating ksql-datagen ... done Creating ksqldb-cli ... done Creating oracle-db ... done Creating redis ... done Verify if all services are up and running. 1 $> docker compose ps -a    If any of the component isn’t up, you can start the individual container using command: 1 $> docker compose start The Oracle container when starting for the first time will take longer time to initialize itself. This will take approx. 15min- 25 mins depending upon the system configuration. Verify status of oracle container using command: 1 $> docker compose logs oracle     Wait till the oracle container is fully initialized with message “DATABASE IS READY TO USE! Oracle DB Configuration After the Oracle database is operational, we must configure it to activate ARCHIVELOG mode, add users, and set up the necessary permissions. Follow the steps mentioned below to setup required configuration on Oracle DB. Connect to Oracle container. 1 $> docker compose exec oracle bash Login to sql server: 1 $> sqlplus ‘/ as sysdba’ Check if Oracle DB is in Archivelog mode. This is needed to extract LogMiner dictionary to the redo logs. 1 2 3 4 5 SQL> select log_mode from v$database; LOG_MODE ------------ ARCHIVELOG    If log_mode is not in archivelog mode, run below commands to enable it. 1 2 3 4 SQL> SHUTDOWN IMMEDIATE; SQL> STARTUP MOUNT; SQL> ALTER DATABASE ARCHIVELOG; SQL> ALTER DATABASE OPEN;    Check again for log_mode. 1 2 3 4 SQL> select log_mode from v$database; LOG_MODE ------------ ARCHIVELOG Create role and grant required Access and permissions. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 CREATE ROLE C##CDC_PRIVS; GRANT EXECUTE_CATALOG_ROLE TO C##CDC_PRIVS; GRANT ALTER SESSION TO C##CDC_PRIVS; GRANT SET CONTAINER TO C##CDC_PRIVS; GRANT SELECT ANY TRANSACTION TO C##CDC_PRIVS; GRANT SELECT ANY DICTIONARY TO C##CDC_PRIVS; GRANT SELECT ON SYSTEM.LOGMNR_COL$ TO C##CDC_PRIVS; GRANT SELECT ON SYSTEM.LOGMNR_OBJ$ TO C##CDC_PRIVS; GRANT SELECT ON SYSTEM.LOGMNR_USER$ TO C##CDC_PRIVS; GRANT SELECT ON SYSTEM.LOGMNR_UID$ TO C##CDC_PRIVS; GRANT CREATE SESSION TO C##CDC_PRIVS; GRANT EXECUTE ON SYS.DBMS_LOGMNR TO C##CDC_PRIVS; GRANT LOGMINING TO C##CDC_PRIVS; GRANT SELECT ON V_$LOGMNR_CONTENTS TO C##CDC_PRIVS; GRANT SELECT ON V_$DATABASE TO C##CDC_PRIVS; GRANT SELECT ON V_$THREAD TO C##CDC_PRIVS; GRANT SELECT ON V_$PARAMETER TO C##CDC_PRIVS; GRANT SELECT ON V_$NLS_PARAMETERS TO C##CDC_PRIVS; GRANT SELECT ON V_$TIMEZONE_NAMES TO C##CDC_PRIVS; GRANT SELECT ON ALL_INDEXES TO C##CDC_PRIVS; GRANT SELECT ON ALL_OBJECTS TO C##CDC_PRIVS; GRANT SELECT ON ALL_USERS TO C##CDC_PRIVS; GRANT SELECT ON ALL_CATALOG TO C##CDC_PRIVS; GRANT SELECT ON ALL_CONSTRAINTS TO C##CDC_PRIVS; GRANT SELECT ON ALL_CONS_COLUMNS TO C##CDC_PRIVS; GRANT SELECT ON ALL_TAB_COLS TO C##CDC_PRIVS; GRANT SELECT ON ALL_IND_COLUMNS TO C##CDC_PRIVS; GRANT SELECT ON ALL_ENCRYPTED_COLUMNS TO C##CDC_PRIVS; GRANT SELECT ON ALL_LOG_GROUPS TO C##CDC_PRIVS; GRANT SELECT ON ALL_TAB_PARTITIONS TO C##CDC_PRIVS; GRANT SELECT ON SYS.DBA_REGISTRY TO C##CDC_PRIVS; GRANT SELECT ON SYS.OBJ$ TO C##CDC_PRIVS; GRANT SELECT ON DBA_TABLESPACES TO C##CDC_PRIVS; GRANT SELECT ON DBA_OBJECTS TO C##CDC_PRIVS; GRANT SELECT ON SYS.ENC$ TO C##CDC_PRIVS; GRANT SELECT ON V_$ARCHIVED_LOG TO C##CDC_PRIVS; GRANT SELECT ON V_$LOG TO C##CDC_PRIVS; GRANT SELECT ON V_$LOGFILE TO C##CDC_PRIVS; GRANT SELECT ON V_$INSTANCE to C##CDC_PRIVS; GRANT SELECT ANY TABLE TO C##CDC_PRIVS; Create user and grant required access. ``` CREATE USER C##MYUSER IDENTIFIED BY password DEFAULT TABLESPACE USERS CONTAINER=ALL; ALTER USER C##MYUSER QUOTA UNLIMITED ON USERS; GRANT C##CDC_PRIVS to C##MYUSER CONTAINER=ALL; GRANT CONNECT TO C##MYUSER CONTAINER=ALL; GRANT CREATE TABLE TO C##MYUSER CONTAINER=ALL; GRANT CREATE SEQUENCE TO C##MYUSER CONTAINER=ALL; GRANT CREATE TRIGGER TO C##MYUSER CONTAINER=ALL; GRANT SELECT ON GV_$ARCHIVED_LOG TO C##MYUSER CONTAINER=ALL; GRANT SELECT ON GV_$DATABASE TO C##MYUSER CONTAINER=ALL; GRANT FLASHBACK ANY TABLE TO C##MYUSER; GRANT FLASHBACK ANY TABLE TO C##MYUSER container=all; 1 2 6. Create Userdata table and Clickstream table. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 CREATE TABLE C##MYUSER.POC_USERDATA ( ID VARCHAR2(50) PRIMARY KEY, NAME VARCHAR2(50) ); GRANT SELECT ON C##MYUSER.POC_USERDATA TO C##CDC_PRIVS; INSERT INTO C##MYUSER.POC_USERDATA (ID, NAME) VALUES ('101', 'jdoe' ); COMMIT; CREATE TABLE C##MYUSER.POC_CLICKSTREAM ( EVENTID VARCHAR2(50) PRIMARY KEY, ID VARCHAR2(50), NAME VARCHAR2(50), SESSIONID VARCHAR2(50), EVENTTYPE VARCHAR2(50), PAGEURL VARCHAR2(255), EVENTTIMESTAMP TIMESTAMP ); GRANT SELECT ON C##MYUSER.POC_CLICKSTREAM TO C##CDC_PRIVS; INSERT INTO C##MYUSER.POC_CLICKSTREAM (EVENTID, ID, NAME, SESSIONID, EVENTTYPE, PAGEURL, EVENTTIMESTAMP) VALUES (1, '101', 'jdoe', 'sess456', 'page_view', 'https://example.com/home', CURRENT_TIMESTAMP); COMMIT; ``` Connector Configuration Check if Oracle Source CDC Connector and Redis Sink connector is enabled and available. 1 $> curl -s -X GET -H 'Content-Type: application/json' http://localhost:8083/connector-plugins | jq '.' The output should contain “class”: “io.confluent.connect.oracle.cdc.OracleCdcSourceConnector” “class”:”com.redis.kafka.connect.RedisSinkConnector” This confirms the source and sink connector plugins are available with Kafka Connector. Configure Oracle CDC Source Connector Create Oracle CDC source connector configuration “userstream_source_connector.json” with content: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 { "name": "userdata_avro", "config":{ "connector.class": "io.confluent.connect.oracle.cdc.OracleCdcSourceConnector", "name": "userdata_avro", "tasks.max":1, "key.converter": "io.confluent.connect.avro.AvroConverter", "key.converter.schema.registry.url": "http://schema-registry:8081", "value.converter": "io.confluent.connect.avro.AvroConverter", "value.converter.schema.registry.url": "http://schema-registry:8081", "confluent.topic.bootstrap.servers":"broker:29092", "oracle.server": "oracle", "oracle.port": 1521, "oracle.sid":"ORCLCDB", "oracle.username": "C##MYUSER", "oracle.password": "password", "start.from":"snapshot", "table.inclusion.regex":"ORCLCDB\\.C##MYUSER\\.POC_USER(.*)", "table.exclusion.regex":"", "table.topic.name.template": "${fullyQualifiedTableName}", "connection.pool.max.size": 20, "confluent.topic.replication.factor":1, "redo.log.consumer.bootstrap.servers":"broker:29092", "redo.log.corruption.topic": "redo-corruption-topic", "topic.creation.groups": "redo", "topic.creation.redo.include": "redo-log-topic", "topic.creation.redo.replication.factor": 1, "topic.creation.redo.partitions": 1, "topic.creation.redo.cleanup.policy": "delete", "topic.creation.redo.retention.ms": 1209600000, "topic.creation.default.replication.factor": 1, "topic.creation.default.partitions": 1, "topic.creation.default.cleanup.policy": "delete", "transforms": "dropExtraFields", "transforms.dropExtraFields.type": "org.apache.kafka.connect.transforms.ReplaceField$Value", "transforms.dropExtraFields.blacklist": "scn, op_type, op_ts, current_ts, row_id, username" } } Similarly create clickstream data source connector configuration json file clickstream_source_connector.json with contents: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 { "name": "clickstream_avro", "config":{ "connector.class": "io.confluent.connect.oracle.cdc.OracleCdcSourceConnector", "name": "clickstream_avro", "tasks.max":1, "key.converter": "io.confluent.connect.avro.AvroConverter", "key.converter.schema.registry.url": "http://schema-registry:8081", "value.converter": "io.confluent.connect.avro.AvroConverter", "value.converter.schema.registry.url": "http://schema-registry:8081", "confluent.topic.bootstrap.servers":"broker:29092", "oracle.server": "oracle", "oracle.port": 1521, "oracle.sid":"ORCLCDB", "oracle.username": "C##MYUSER", "oracle.password": "password", "start.from":"snapshot", "table.inclusion.regex":"ORCLCDB\\.C##MYUSER\\.POC_CLICK(.*)", "table.exclusion.regex":"", "table.topic.name.template": "${fullyQualifiedTableName}", "connection.pool.max.size": 20, "confluent.topic.replication.factor":1, "redo.log.consumer.bootstrap.servers":"broker:29092", "redo.log.corruption.topic": "redo-corruption-topic", "topic.creation.groups": "redo", "topic.creation.redo.include": "redo-log-topic", "topic.creation.redo.replication.factor": 1, "topic.creation.redo.partitions": 1, "topic.creation.redo.cleanup.policy": "delete", "topic.creation.redo.retention.ms": 1209600000, "topic.creation.default.replication.factor": 1, "topic.creation.default.partitions": 1, "topic.creation.default.cleanup.policy": "delete", "transforms": "dropExtraFields", "transforms.dropExtraFields.type": "org.apache.kafka.connect.transforms.ReplaceField$Value", "transforms.dropExtraFields.blacklist": "scn, op_type, op_ts, current_ts, row_id, username" } } Configure Redis Sink Connector Create Redis sink connector redis_sink.json using configuration: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 { "name": "redis-sink-json", "config": { "connector.class":"com.redis.kafka.connect.RedisSinkConnector", "tasks.max":"1", "topics":"USER_AGGREGATE_EVENTS", "redis.uri":"redis://redis:6379", "redis.command":"JSONSET", "key.converter": "io.confluent.connect.avro.AvroConverter", "key.converter.schema.registry.url": "http://schema-registry:8081", "value.converter": "io.confluent.connect.avro.AvroConverter", "value.converter.schema.registry.url": "http://schema-registry:8081", "schemas.enable": "false" } } Start connector based on the configuration created above 1 2 3 $> curl -s -X POST -H 'Content-Type: application/json' --data @userstream_source_connector.json http://localhost:8083/connectors | jq $> curl -s -X POST -H 'Content-Type: application/json' --data @clickstream_source_connector.json http://localhost:8083/connectors | jq $> curl -s -X POST -H 'Content-Type: application/json' --data @redis_sink.json http://localhost:8083/connectors | jq Verify status of Source and Sink Connectors. 1 2 3 $> curl -s -X GET -H 'Content-Type: application/json' http://localhost:8083/connectors/userdata_avro/status | jq $> curl -s -X GET -H 'Content-Type: application/json' http://localhost:8083/connectors/clickstream_avro/status | jq $> curl -s -X GET -H 'Content-Type: application/json' http://localhost:8083/connectors/redis-sink-json/status | jq With the userdata and clickstream source connector configured, the Oracle CDC source connector continuously monitors database, creating an event stream for any changes. Create Stream Processing using ksqlDB Query Login to Confluent Control Center using http://:9021 Navigate to Cluster Overview → ksqlDB. In ksqlDB editor, set “auto.offset.reset”=”earliest” and enter below query to create Streams and Tables. Click “Run query” button to submit. 1 2 3 4 5 6 7 8 CREATE TABLE POC_USERDATA_STREAM ( ID STRING PRIMARY KEY, NAME STRING ) WITH ( KAFKA_TOPIC = 'ORCLCDB.C__MYUSER.POC_USERDATA', KEY_FORMAT = 'AVRO', VALUE_FORMAT = 'AVRO' ); 1 2 3 4 5 6 7 8 9 10 11 12 13 CREATE STREAM POC_CLICKSTREAM_STREAM ( EVENTID STRING, ID STRING, NAME STRING, SESSIONID STRING, EVENTTYPE STRING, PAGEURL STRING, EVENTTIMESTAMP BIGINT ) WITH ( KAFKA_TOPIC = 'ORCLCDB.C__MYUSER.POC_CLICKSTREAM', KEY_FORMAT = 'AVRO', VALUE_FORMAT = 'AVRO' ); 1 2 3 4 5 6 7 8 9 10 11 CREATE TABLE USER_AGGREGATE_EVENTS WITH ( KEY_FORMAT = 'AVRO', VALUE_FORMAT = 'AVRO' ) AS SELECT NAME, COUNT(*) AS EVENT_COUNT FROM POC_CLICKSTREAM_STREAM WINDOW TUMBLING (SIZE 1 MINUTE) GROUP BY NAME; The Stream and Table created can be verified by navigating to ksqlDB –> Streams or ksqlDB –> Tables on Control Center GUI. Userstream and Clickstream tables in Oracle DB must be updated in order to confirm that Oracle CDC Source Connector reads database changes. Connect to Oracle Container and update tables. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 $> docker compose exec oracle bash $> sqlplus ‘/ as sysdba’ SQL> INSERT INTO C##MYUSER.POC_USERDATA (ID, NAME) VALUES ('102', 'rsmith'); INSERT INTO C##MYUSER.POC_USERDATA (ID, NAME) VALUES ('103', 'amary'); INSERT INTO C##MYUSER.POC_USERDATA (ID, NAME) VALUES ('104', 'jwick'); INSERT INTO C##MYUSER.POC_USERDATA (ID, NAME) VALUES ('105', 'jcena'); INSERT INTO C##MYUSER.POC_CLICKSTREAM (EVENTID, ID, NAME, SESSIONID, EVENTTYPE, PAGEURL, EVENTTIMESTAMP) VALUES (2, '101', 'jdoe', 'sess456', 'click', 'https://example.com/product/123', CURRENT_TIMESTAMP); INSERT INTO C##MYUSER.POC_CLICKSTREAM (EVENTID, ID, NAME, SESSIONID, EVENTTYPE, PAGEURL, EVENTTIMESTAMP) VALUES (3, '101', 'jdoe', 'sess456', 'click', 'https://example.com/product/125', CURRENT_TIMESTAMP); INSERT INTO C##MYUSER.POC_CLICKSTREAM (EVENTID, ID, NAME, SESSIONID, EVENTTYPE, PAGEURL, EVENTTIMESTAMP) VALUES (4, '102', 'rsmith', 'sess789', 'click', 'https://example.com/about', CURRENT_TIMESTAMP); INSERT INTO C##MYUSER.POC_CLICKSTREAM (EVENTID, ID, NAME, SESSIONID, EVENTTYPE, PAGEURL, EVENTTIMESTAMP) VALUES (5, '102', 'rsmith', 'sess101', 'click', 'https://example.com/checkout', CURRENT_TIMESTAMP); INSERT INTO C##MYUSER.POC_CLICKSTREAM (EVENTID, ID, NAME, SESSIONID, EVENTTYPE, PAGEURL, EVENTTIMESTAMP) VALUES (6, '103', 'amary', 'sess101', 'click', 'https://example.com/checkout', CURRENT_TIMESTAMP); INSERT INTO C##MYUSER.POC_CLICKSTREAM (EVENTID, ID, NAME, SESSIONID, EVENTTYPE, PAGEURL, EVENTTIMESTAMP) VALUES (7, '103', 'amary', 'sess101', 'click', 'https://example.com/checkout', CURRENT_TIMESTAMP); COMMIT; The events added in the previous step create clickstream events and aggregate based on userid. Testing Redis Sink Connector The aggregated clickstream events can be verified in Redis since Redis Sink connector would read events from aggregated event table. 1 2 3 4 5 $> docker compose exec redis bash -c “redis-cli json.get USER_AGGREGATE_EVENTS:jdoe” $> docker compose exec redis bash -c “redis-cli json.get USER_AGGREGATE_EVENTS:rsmith” $> docker compose exec redis bash -c “redis-cli json.get USER_AGGREGATE_EVENTS:amary” $> docker compose exec redis bash -c “redis-cli json.get USER_AGGREGATE_EVENTS:jwick” $> docker compose exec redis bash -c “redis-cli json.get USER_AGGREGATE_EVENTS:jcena” Clean up To clean up your setup, you can run below command which will stop all running containers and remove any volumes used by container. 1 $> docker compose down -v Conclusion This showcases an end-to-end data streaming pipeline using the Confluent Platform, involving key components like the Kraft Controller, Kafka Broker, Kafka Connect with Oracle CDC Source and Redis Sink connectors, Schema Registry, ksqlDB, and Confluent Control Center. Data from two Oracle tables (Users and Clickstream) is captured using the Oracle CDC Source connector, published to Kafka topics in Avro format, and schemas are stored in the Schema Registry. A ksqlDB query processes the Clickstream data, aggregating clicks within a time window and sending the results to a new Kafka topic. Using the Redis Kafka Sink Connector, this processed data is then transferred to Redis. The Confluent Control Center is used to monitor the entire data flow, ensuring smooth operation from Oracle to Kafka to Redis. Reference Quick Start for the Oracle CDC Source Connector for Confluent Platform Oracle Database Prerequisites Quick Start for Confluent Platform --- # How to integrate WASM with Redpanda URL: https://platformatory.io/blog/integrate-WASM-with-Redpanda/ Published: 2024-09-23 Authors: Zeenia Gupta Categories: Redpanda, Stream Processing, WASM How to integrate WASM with Redpanda Introduction Redpanda Redpanda is a fully-featured streaming data platform compatible with Apache Kafka, built from scratch to be more lightweight, faster, and easier to manage. Free from Zookeeper and JVM, it prioritizes an end-to-end developer experience with a huge ecosystem of connectors, configurable tiered storage, and more. Redpanda is highly efficient at processing and streaming large volumes of real-time data with minimal latency, handling high-throughput workloads effectively. Its user-friendly command-line interface (CLI) is designed to be straightforward, making real-time data management simpler and more efficient. What is WASM (WebAssembly)? WASM, or WebAssembly, is a lightweight technology that allows users to write transformations in any supported WASM languages like C, C++, Rust, and many more. It can also run within other applications. It integrates seamlessly with JavaScript while ensuring a secure environment, making it perfect for performance-critical applications. With WASM, developers can create high-performance, scalable web applications with greater flexibility and efficiency. How do Redpanda and WASM work together? Integrating WASM with Redpanda allows you to perform data transformations directly on the Kafka broker. This enables engineers to read data, prepare messages, and make API calls within brokers, avoiding unnecessary data transfers. Redpanda Data Transforms which is built on the WASM engine and lets you run a piece of code (.wasm) on chosen data (topics), on location, triggered by events in an auditable. To read more about this architecture, check out this document For example, you might set up an Apache Kafka Streams application process and filter JSON events from your ecommerce website in real time, removing sensitive credit card information before storing or further processing them. With WASM, you can perform similar transformations directly within the Repanda broker itself. WASM allows you to write custom processing logic in various languages, such as JavaScript in this example and compile it to the WASM module. This module can then be executed inside Redpanda, enabling you to filter, transform or aggregate data directly as it streams through the broker. This approach reduces the need for external processing frameworks and can improve the performance by integrating data transformations directly into the streaming pipeline. Benefits of WASM for Stream Processing High Performance: WASM modules with high speed, providing high performance for data processing tasks. This is crucial for handling large volumes of streaming data with minimal latency. Portability: WASM is designed to run consistently across different platforms and environments. This allows you to deploy stream processing login in various systems without modification. Security: WASM operates in a secure, isolated environment, reducing the risk of malicious attack as it doesn’t allow disk read/write. This ensures that stream processing tasks are executed in a controlled and safe manner. Reduce Overhead: WASM is lightweight compared to traditional virtual machines, which translates into lower resource consumption and faster startup times. This is beneficial for real-time stream processing where efficiency is crucial. Multi-Language Support: WASM supports multiple programming languages, allowing developers to use the most appropriate language for their processing logic. Use Cases for WASM Real-Time Data Formatting: Use WASM to perform real-time data transformations, such as converting JSON to AVRO, or other formats directly within Redpanda. This minimizes the need for external processing frameworks and reduces data latency. For an example of transforming JSON formatted messages to an AVRO schema, check out example Sanitizing Input Data: Apply WASM to remove or alter sensitive data in real time before it is processed or stored. This ensures sensitive information is protected and compiles with data privacy regulations. You can check the example below, where we are removing the credit card details. Efficient Computation: Offload computationally intensive tasks to WASM to take advantage of its near-native performance. This helps to optimize the overall performance of a stream processing pipeline. Setting up Redpanda for WASM development This example uses the async engine to map the messages and filter out the credit card information based on the user input. We are running Redpanda service as a docker container. We have created a docker compose file, which creates the docker container for the Redpanda, 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 networks: redpanda_network: driver: bridge ipam: config: - subnet: 172.24.1.0/24 gateway: 172.24.1.1 services: redpanda: command: - redpanda - start - --node-id 0 - --smp 1 - --memory 1G - --overprovisioned image: docker.vectorized.io/vectorized/redpanda:v21.12.1-wasm-beta1 container_name: redpanda networks: redpanda_network: ipv4_address: 172.24.1.2 volumes: - ./redpanda-wasm.yaml:/etc/redpanda/redpanda.yaml - ../wasm/js/transform_avro:/etc/redpanda/wasm/js/transform_avro - ../clients:/etc/redpanda/clients ports: - 8081:8081 # Schema registry port - 8082:8082 # Pandaproxy port - 9092:9092 # Kafka API port - 9644:9644 # Prometheus and HTTP admin port This example JavaScript transform uses the async engine to map JSON formatted messages to an AVRO schema. Start Redpanda Container 1 docker compose -f docker-compose/compose-wasm.yml up -d Install the node.js in the Redpanda Container 1 docker exec --user root -it redpanda /bin/bash 1 2 curl -fsSL https://deb.nodesource.com/setup_17.x | bash - apt-get install -y nodejs Build & Deploy Coproc Create the js file to filter out the credit card detail from the data based on the variable “not_store_bank_info” within a stream processing environment. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 const { SimpleTransform, PolicyError, PolicyInjection, calculateRecordBatchSize } = require("@vectorizedio/wasm-api"); // Define the variable to control the inclusion of credit card info const not_store_bank_info = process.env.NOT_STORE_BANK_INFO || "yes"; const transform = new SimpleTransform(); /** * Topics that fire the transform function * - Earliest * - Stored * - Latest */ transform.subscribe([["customer_data", PolicyInjection.Latest]]); /** * The strategy the transform engine will use when handling errors * - SkipOnFailure * - Deregister */ transform.errorHandler(PolicyError.SkipOnFailure); /* Auxiliary transform function for records */ const transformToJSON = (record) => { const obj = JSON.parse(record.value); if (not_store_bank_info === "yes") { delete obj.CreditCardNumber;// Remove credit card info if not storing } //console.log("After transformation: ", obj); //console.log("Record: ", record); const newRecord = { ...record, value: Buffer.from(JSON.stringify(obj)), }; //console.log("newRecord: ", newRecord); return newRecord; } /* Transform function */ transform.processRecord((batch) => { const result = new Map(); const transformedBatch = batch.map(({ header, records }) => { const transformedRecords = records.map(transformToJSON); return { header, records: transformedRecords, }; }); result.set("json",transformedBatch); // Set the transformed data as JSON // processRecord function returns a Promise return Promise.resolve(result); }); exports["default"] = transform; This script is a Node.js script for dynamically configuring and running Webpack to bundle JavaScript file. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 #!/usr/bin/env node const webpack = require("webpack"); const fs = require("fs"); fs.readdir("./src/", (err, files) => { if (err) { console.log(err); return; } const webPackOptions = files.map((fileName) => { return { mode: "production", entry: { main: `./src/${fileName}` }, output: { filename: fileName, libraryTarget: "commonjs2", }, performance: { hints: false }, target: 'node', }; }); webpack(webPackOptions, (err, stat) => { if (err) { console.log(err); } const info = stat.toJson(); if (stat.hasErrors()) { console.error(info.errors); } if (stat.hasWarnings()) { console.warn(info.warnings); } }); }); Run the following commands 1 2 3 4 5 6 7 cd wasm/js/transform_avro # install js dependencies in node_modules npm install # bundle js application with Webpack npm run build Create the topic 1 rpk topic create customer_data Output 1 2 TOPIC STATUS customer_data OK List the topic 1 rpk topic list Output 1 2 NAME PARTITIONS REPLICAS customer_data 1 1 Deploy the transform script to Redpanda 1 rpk wasm deploy dist/main.js --name customer_data --description "Getting the customer data" Output 1 Deploy successful! Produce JSON Records and Consume AVRO Results Start two consumers (run each command below in a separate terminal) 1 2 rpk topic consume customer_data rpk topic consume customer_data._json_ Start the producer (in a third terminal) producer.js 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 import chalk from "chalk"; import csv from "csv-parser"; import parseArgs from "minimist"; import path from "path"; import { addDays } from "date-fns"; import { createReadStream } from "fs"; import { Kafka } from "kafkajs"; let args = parseArgs(process.argv.slice(2)); const help = ` ${chalk.red("customer_data.js")} - Produce events to an event bus by reading data from a CSV file ${chalk.bold("USAGE")} > node produce_customer_data.js --help > node produce_customer_data.js [-f path_to_file] [-t topic_name] [-b host:port] [-d date_column_name] [-r] [-l] By default, the producer script will stream data from customer_data.csv and output events to a topic named customer_data. If either the loop or reverse arguments are given, file content is read into memory prior to sending events. Don't use the loop/reverse arguments if the file size is large or your system memory capacity is low. ${chalk.bold("OPTIONS")} -h, --help Shows this help message -f, --file, --csv Reads from file and outputs events to a topic named after the file default: ../../data/customer_data.csv -t, --topic Topic where events are sent default: customer_data -b, --broker --brokers Comma-separated list of the host and port for each broker default: localhost:9092 -d, --date Date is turned into an ISO string and incremented during loop default: Date -r, --reverse Read file into memory and then reverse -l, --loop Read file into memory and then loop continuously ${chalk.bold("EXAMPLES")} Stream data from the default file and output events to the default topic on the default broker: > node produce_customer_data.js Stream data from data.csv and output to a topic named data on broker at brokerhost.dev port 19092: > node produce_customer_data.js -f data.csv -b brokerhost.dev:19092 Read data from the default file and output events to the default topic on broker at localhost port 19092: > node produce_customer_data.js --brokers localhost:19092 Read data from the default file into memory, reverse contents, and send events to the default topic on broker at localhost port 19092: > node produce_customer_data.js -rb localhost:19092 Read data from the default file into memory, reverse contents, output ISO date string for Date prop: > node produce_customer_data.js --brokers localhost:19092 --reverse --date Date Same as above, but loop continuously and increment the date by one day on each event: > node produce_customer_data.js -lrb localhost:19092 -d Date `; if (args.help || args.h) { console.log(help); process.exit(0); } const brokers = (args.brokers || args.b || "localhost:19092").split(","); const csvPath = args.csv || args.file || args.f || "/etc/redpanda/clients/js/customer_data.csv"; const topic = args.topic || args.t || path.basename(csvPath, ".csv") || path.basename(csvPath, ".CSV"); const dateProp = args.date || args.d; const isReverse = args.reverse || args.r; const isLoop = args.loop || args.l; const redpanda = new Kafka({ clientId: "example-customer-producer-js", brokers, }); const producer = redpanda.producer(); /* Produce single message */ const send = async (obj) => { try { const json = JSON.stringify(obj); await producer.send({ topic: topic, messages: [{ value: json }], }); console.log(`Produced: ${json}`); } catch (e) { console.error(e); } }; const run = async () => { let lastDate; console.log("Producer connecting..."); await producer.connect(); let data = []; // Transform each CSV row as JSON and send to Redpanda createReadStream(csvPath) .pipe(csv()) .on("data", function (row) { if (dateProp) { if (!row[dateProp]) { throw new Error("Invalid date argument (-d, --date). Must match an existing column."); } row[dateProp] = new Date(row[dateProp]); } if (isLoop || isReverse) { // set last date if we have a date prop, and either if 1) we are on the first entry while reversed or 2) not reversed if (dateProp && ((isReverse && !lastDate) || !isReverse)) lastDate = row[dateProp]; data.push(row); } else { send(row); } }) .on("end", async function () { if (isLoop || isReverse) { if (isReverse) data.reverse(); for (let i = 0; i < data.length; i++) { await send(data[i]); } while (isLoop) { for (let i = 0; i < data.length; i++) { if (dateProp) data[i][dateProp] = lastDate = addDays(lastDate, 1); await send(data[i]); } } } }); }; run().catch((e) => console.error(e)); /* Disconnect on CTRL+C */ process.on("SIGINT", async () => { try { console.log("\nProducer disconnecting..."); await producer.disconnect(); process.exit(0); } catch (_) { process.exit(1); } }); 1 2 3 cd clients/js npm install node producer.js -rd Date Note: The topic customer_data.json doesn’t exist, but it will be automatically created once the WASM function begins consuming events from the topic customer_data. Output After starting the producer Output from customer_data The output will contain many lines of JSON string representations of the events being sent to the topic customer_data. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 { "topic": "customer_data", "value": "{\"CustomerID\":\"1\",\"FirstName\":\"John\",\"LastName\":\"Doe\",\"Email\":\"john.doe@example.com\",\"Phone\":\"+1234567890\",\"Address\":\"123 Elm St\",\"City\":\"Springfield\",\"State\":\"IL\",\"PostalCode\":\"62701\",\"Country\":\"USA\",\"CreditCardNumber\":\"4111111111111111\",\"OrderTotal\":\"150.00\",\"LastPurchaseDate\":\"2024-09-05\"}", "timestamp": 1727180609623, "partition": 0, "offset": 0 } { "topic": "customer_data", "value": "{\"CustomerID\":\"2\",\"FirstName\":\"Jane\",\"LastName\":\"Smith\",\"Email\":\"jane.smith@example.com\",\"Phone\":\"+0987654321\",\"Address\":\"456 Oak St\",\"City\":\"Lincoln\",\"State\":\"NE\",\"PostalCode\":\"68508\",\"Country\":\"USA\",\"CreditCardNumber\":\"5500000000000004\",\"OrderTotal\":\"200.00\",\"LastPurchaseDate\":\"2024-09-07\"}", "timestamp": 1727180609626, "partition": 0, "offset": 1 } { "topic": "customer_data", "value": "{\"CustomerID\":\"3\",\"FirstName\":\"Bob\",\"LastName\":\"Johnson\",\"Email\":\"bob.johnson@example.com\",\"Phone\":\"+1122334455\",\"Address\":\"789 Pine St\",\"City\":\"Columbus\",\"State\":\"OH\",\"PostalCode\":\"43215\",\"Country\":\"USA\",\"CreditCardNumber\":\"340000000000009\",\"OrderTotal\":\"120.00\",\"LastPurchaseDate\":\"2024-09-08\"}", "timestamp": 1727180609627, "partition": 0, "offset": 2 } Output from customer_data.json The output will be the string representations of the json-serialized data where we filter the credit card number events being sent to customer_data.json 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 { "topic": "customer_data._json_", "value": "{\"CustomerID\":\"1\",\"FirstName\":\"John\",\"LastName\":\"Doe\",\"Email\":\"john.doe@example.com\",\"Phone\":\"+1234567890\",\"Address\":\"123 Elm St\",\"City\":\"Springfield\",\"State\":\"IL\",\"PostalCode\":\"62701\",\"Country\":\"USA\",\"OrderTotal\":\"150.00\",\"LastPurchaseDate\":\"2024-09-05\"}", "timestamp": 1727180609623, "partition": 0, "offset": 0 } { "topic": "customer_data._json_", "value": "{\"CustomerID\":\"2\",\"FirstName\":\"Jane\",\"LastName\":\"Smith\",\"Email\":\"jane.smith@example.com\",\"Phone\":\"+0987654321\",\"Address\":\"456 Oak St\",\"City\":\"Lincoln\",\"State\":\"NE\",\"PostalCode\":\"68508\",\"Country\":\"USA\",\"OrderTotal\":\"200.00\",\"LastPurchaseDate\":\"2024-09-07\"}", "timestamp": 1727180609626, "partition": 0, "offset": 1 } { "topic": "customer_data._json_", "value": "{\"CustomerID\":\"3\",\"FirstName\":\"Bob\",\"LastName\":\"Johnson\",\"Email\":\"bob.johnson@example.com\",\"Phone\":\"+1122334455\",\"Address\":\"789 Pine St\",\"City\":\"Columbus\",\"State\":\"OH\",\"PostalCode\":\"43215\",\"Country\":\"USA\",\"OrderTotal\":\"120.00\",\"LastPurchaseDate\":\"2024-09-08\"}", "timestamp": 1727180609627, "partition": 0, "offset": 2 } Output from the producer terminal 1 2 3 4 5 6 7 8 9 Producer connecting... Produced: {"CustomerID":"1","FirstName":"John","LastName":"Doe","Email":"john.doe@example.com","Phone":"+1234567890","Address":"123 Elm St","City":"Springfield","State":"IL","PostalCode":"62701","Country":"USA","CreditCardNumber":"4111111111111111","OrderTotal":"150.00","LastPurchaseDate":"2024-09-05"} Produced: {"CustomerID":"2","FirstName":"Jane","LastName":"Smith","Email":"jane.smith@example.com","Phone":"+0987654321","Address":"456 Oak St","City":"Lincoln","State":"NE","PostalCode":"68508","Country":"USA","CreditCardNumber":"5500000000000004","OrderTotal":"200.00","LastPurchaseDate":"2024-09-07"} Produced: {"CustomerID":"3","FirstName":"Bob","LastName":"Johnson","Email":"bob.johnson@example.com","Phone":"+1122334455","Address":"789 Pine St","City":"Columbus","State":"OH","PostalCode":"43215","Country":"USA","CreditCardNumber":"340000000000009","OrderTotal":"120.00","LastPurchaseDate":"2024-09-08"} Produced: {"CustomerID":"4","FirstName":"Emily","LastName":"Williams","Email":"emily.williams@example.com","Phone":"+2233445566","Address":"101 Maple St","City":"Denver","State":"CO","PostalCode":"80202","Country":"USA","CreditCardNumber":"6011000000000004","OrderTotal":"250.00","LastPurchaseDate":"2024-09-06"} Produced: {"CustomerID":"5","FirstName":"Michael","LastName":"Brown","Email":"michael.brown@example.com","Phone":"+3344556677","Address":"202 Birch St","City":"Seattle","State":"WA","PostalCode":"98101","Country":"USA","CreditCardNumber":"213141413141141","OrderTotal":"180.00","LastPurchaseDate":"2024-09-04"} ^C Producer disconnecting... Conclusion Integrating WebAssembly (WASM) with Redpanda provides a powerful solution for efficient stream processing. Redpanda’s high-performance, Kafka-compatible platform combined with WASM’s lightweight, fast execution enables you to perform complex, real-time data transformations directly within the broker. This integration reduces latency, minimizes overhead, and enhances security, streamlining your data processing pipeline and improving overall performance. By following the steps in this guide, you can leverage WASM to optimize and customize your data streaming workflows effectively. --- # Migrating from Kafka Connect to Redpanda Connect URL: https://platformatory.io/blog/migrating-kafka-connect-to-redpanda/ Published: 2024-09-10 Authors: Zeenia Gupta, Shivaprakash Akki Categories: Redpanda, Kafka Connect, Migration Migrating from kafka Connect to Redpanda Connect Introduction Redpanda Connect Redpanda Connect previously known as benthos is a lightweight stream-processing framework for building data pipelines. It contains many different types of input and output connectors and provides transformation capabilities via a custom language called Bloblang. It is designed for handling and transforming large amounts of data in real time, making it ideal for use cases like ETL (Extract, Transform and Load) pipelines, log processing, data enrichment, and more. It can complement these traditional data engineering tools or act as a simpler alternative. Bloblang Bloblang is a language used mainly for data transformation. It allows users to define complex data transformations with easy-to-understand syntax. Writing code in Bloblang can be straightforward for those familiar with programming concepts, as it provides a set of functions and operators to manipulate data. The language is designed to be clear and simple to use. Kafka Connect Kafka Connect is a flexible, declarative framework for integration data with Kafka. It connects data sources and sinks to Kafka, allowing the rest of the Kafka ecosystem to efficiently manage event streams. With hundreds of connectors available, Kafka Connect simplifies streaming data from various sources into Kafka and from Kafka into different destinations. A common Kafka Connect use case is orchestrating real-time event streams from a data source to a target system for analytics. Why Choose Redpanda Connect over Kafka Connect? Redpanda Connect may be a better fit than Kafka Connect in scenarios where you need more flexibility and control over data transformations, particularly when you’re dealing with complex process logic. Repanda offers a framework for creating and deploying inline transformations (data transforms) directly within Redpanda topics. This enables the processing and validation of data right inside the broker, so that consumers receive data in the format they expect. By handling transformations within the broker itself, Redpanda eliminates the need for managing separate stream processing environments or relying on third-party tools. You can read more about it here. It’s also a strong choice for building data pipelines outside of the Kafka ecosystem. When building data integration pipelines, we rarely send data in exactly the same way. While Kafka Connect offers SMTs (Single Message Transforms) for simple, stateless transformations like filtering, projecting or routing messages, more complex tasks require a stream-processing framework like Kafka Streams, which can add significant overhead. Redpanda Connect, however, offers a more lightweight alternative by exposing data ingestion endpoints over HTTP(s) allowing you to send and receive data via standard HTTP requests. This enables seamless integration with non-Kafka systems or microservices, making data ingestion and transformation more efficient without the need for additional infrastructure. Additionally, Redpanda Connect offers superior performance in lightweight, high-throughput environments due to its streamlined architecture and efficient Go-based design. If your use case requires advanced data transformations, or operates in an environment where minimizing overhead is crucial, Redpanda Connect is likely the better choice. Its architecture is optimized for handling transformations more efficiently, with lower latency and less overhead, and is ideal for high-throughput environments. While Kafka Connect is reliable, it can be more resource-intensive due to its Java-based system, which may slow things down when processing large volumes of data or complex operations. Migrating Connectors Understanding Source and Sink Connectors in Kafka Connect Source Connector: Source connector pulls data from an external system (e.g., databases, message queues) and pushes into the Kafka topics. Source connector can also collect metrics from all your application servers and store the data in Kafka topics. Sink Connector: Sink connector delivers the data from Kafka topics to external systems, such as Elasticsearch, or batch systems, ensuring that processed or raw data can be stored or further processed. Migrating Kafka Connect Pipeline to Redpanda Connect Workflow: We are running kafka, Benthos, ClickHouse, and zookeeper as docker containers. We have created a docker compose file, which creates the docker container for all these services mentioned above. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 --- version: '3.7' services: zookeeper1: image: confluentinc/cp-zookeeper:7.6.2 hostname: zookeeper1 container_name: zookeeper1 ports: - "2181:2181" command: zookeeper-server-start /etc/kafka/zookeeper.properties volumes: - ./zookeeper1:/etc/kafka deploy: resources: limits: cpus: "1" memory: 512M kafka1: image: confluentinc/cp-server:7.6.2 hostname: kafka1 container_name: kafka1 depends_on: - zookeeper1 command: kafka-server-start /etc/kafka/server.properties volumes: - ./kafka1:/etc/kafka deploy: resources: limits: cpus: "1.5" memory: 1536M connect: image: confluentinc/cp-server-connect:7.6.2 hostname: connect container_name: connect depends_on: - kafka1 command: connect-distributed /etc/kafka/connect-distributed.properties ports: - "8083:8083" volumes: - ./connect:/etc/kafka - ./plugins:/usr/share/java deploy: resources: limits: cpus: "2" memory: 4G clickhouse: image: clickhouse/clickhouse-server hostname: clickhouse container_name: clickhouse ports: - "8123:8123" - "9000:9000" # if you need the native client port volumes: - clickhouse-data:/var/lib/clickhouse - clickhouse-config:/etc/clickhouse-server benthos: image: jeffail/benthos:latest hostname: benthos container_name: benthos volumes: - ./benthos.yaml:/benthos.yaml ports: - "4195:4195" depends_on: - kafka1 - clickhouse volumes: clickhouse-data: clickhouse-config: Step-by-Step Guide Let’s walk through an example of migrating Kafka Connect pipeline that reads data from Kafka topic, performs an aggregation and writes the data to a ClickHouse database. Migrating to Redpanda Connect Create the Kafka Topic: 1 kafka-topic.sh --bootstrap-server localhost:19092 --create --topic benthos Produce the data into a Kafka topic 1 kafka-console-producer.sh --bootstrap-server localhost:19092 --topic benthos Create the Table in ClickHouse Set Database Context: You can set the database context in your connection string if your client supports it: 1 clickhouse-client --user default --password '' --host localhost --port 9000 --query "USE default" Create Table: If the table does not exist, create it with the following commands 1 2 3 4 5 clickhouse-client --user default --password '' --host localhost --port 9000 --query " CREATE TABLE default.benthos ( table_benthos Float64 ) ENGINE = MergeTree() ORDER BY tuple();" Describe Table: If the table exists, describe it to ensure the schema is correct. 1 clickhouse-client --user default --password '' --host localhost --port 9000 --query "DESCRIBE TABLE default.benthos" List Tables: Check if the ‘benthos’ table exists in the ‘default’ database. 1 clickhouse-client --user default --password '' --host localhost --port 9000 --query "SHOW TABLES FROM default" Query Table: If the table exists and is described correctly, run the query to select data from it. 1 clickhouse-client --user default --password '' --host localhost --port 9000 --query "SELECT * FROM default.benthos" Write the Redpanda Connect configuration file 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 --- input: kafka: addresses: - kafka1:19092 topics: [ benthos ] consumer_group: benthos_group client_id: benthos_client start_from_oldest: true tls: {} sasl: {} pipeline: processors: - bloblang: | root = this * this output: sql_insert: driver: clickhouse dsn: clickhouse://default:@clickhouse:9000/default table: benthos columns: - "table_benthos" args_mapping: root = [ this ] max_in_flight: 64 batching: count: 100 period: 5s Define the Input Configuration The Redpanda Connect configuration will start with an input section that consumed messages from a Kafka topic. 1 2 3 4 5 6 7 8 9 10 11 --- input: kafka: addresses: - kafka1:19092 topics: [ benthos ] consumer_group: benthos_group client_id: benthos_client start_from_oldest: true tls: {} sasl: {} Configure Data Transformation Next, use Bloblang to define the transformation logic. 1 2 3 4 pipeline: processors: - bloblang: | root = this * this Define the Output Configuration Finally, set up the output section to write to ClickHouse using the SQL insert processor. 1 2 3 4 5 6 7 8 9 10 11 12 output: sql_insert: driver: clickhouse dsn: clickhouse://default:@clickhouse:9000/default table: benthos columns: - "table_benthos" args_mapping: root = [ this ] max_in_flight: 64 batching: count: 100 period: 5s Format of dsn that used to connect with the benthos and send the data from topic to click house table. 1 dsn: clickhouse://default:@:9000/ Output As shown in the following output, the pipeline reads messages from Kafka topic i.e. benthos and processes each message by squaring its value. This transformation is handled by Redpanda Connect’s Blobland language, which allows flexible data manipulation within the pipeline. The processed data is then inserted into a ClickHouse table in batches of 100 messages or every 5 seconds, whichever occurs first. Conclusion When migrating from Kafka Connect to Redpanda Connect, it’s essential to evaluate several factors to ensure a successful transition. Redpanda Connect enhances flexibility and control over data transformations, making it suitable for scenarios involving complex processing logic or when operating outside the Kafka ecosystem. However, Kafka Connect remains a robust choice in situations where its extensive ecosystem of connectors and seamless integration with Kafka’s event streams are advantageous. Before making a full commitment to Redpanda Connect, it’s important to understand your needs, allowing you to test and validate its capabilities in your environment. This careful evaluation will help ensure that your chosen tool aligns with your data processing requirements and operational goals. --- # Confluent Tableflow: Bridging Operational and Analytical Data URL: https://platformatory.io/blog/confluent-tableflow-bridging-operational-and-analytical-data/ Published: 2024-09-10 Authors: Sathishkumar Venkatesan Categories: Confluent Cloud, Data Engineering, Lakehouse, Kafka The Current Divide in Data Processing In today’s fast-paced world, businesses rely on two main types of data: operational and analytical. However, a significant problem is that these two types of data have traditionally been kept separate, leading to various challenges. These challenges include data latency caused by moving data between different systems, the cost and complexity of maintaining separate systems, and the need to manage complex data pipelines for synchronizing operational and analytical data. Operational data is what keeps your business running day-to-day. It comes from real-time applications, SaaS platforms, and databases. On the other hand, analytical data is used for making business decisions and is stored in data warehouses, lakes, and analytics tools. The problem is that moving data between these two types of systems is complex, slow, and expensive. You have to extract, transform, and load (ETL) the data from operational systems to analytical ones, which takes time and resources. This means your data is often outdated by the time it’s ready for analysis, leading to delays and inefficiencies. The Role of Apache Iceberg and Confluent Tableflow Confluent saw this problem and introduced Tableflow—a new feature that helps bridge the gap between operational and analytical data. And the key to this is Apache Iceberg, an open table format that’s become a standard for managing large datasets in data lakes and warehouses. How Apache Iceberg Bridges the Gap Apache Iceberg plays a crucial role in bringing these two types of data together. It provides a powerful, open format that allows data to be shared across different platforms and always kept up to date. For example, consider an e-commerce platform where operational data consists of user transactions, including transaction IDs, user IDs, product IDs, timestamps, and amounts. With Iceberg, this data can be stored in a unified table format: transaction_id user_id product_id timestamp amount event_type partition 1001 2001 3001 2024-09-04 10:01:23.123 20 purchase 2024-09-04 1002 2002 3002 2024-09-04 10:10:20.123 10 purchase 2024-09-04 1003 2003 3003 2024-09-04 10:15:00.000 05 refund 2024-09-04 1004 2004 3004 2024-09-04 10:16:23.123 50 purchase 2024-09-04 With Iceberg, the same data that powers real-time applications can also be stored as tables in a data lake, making it ready for analytical tools without the need for complicated ETL processes. This approach ensures that both operational and analytical queries can access the latest data, bridging the gap between these traditionally separate types of data. How Tableflow Makes It Easy Tableflow allows you to turn Apache Kafka topics directly into Iceberg tables with just a click. What makes this even more powerful is that Tableflow leverages object storage as its backend. Object storage is ideal for handling large amounts of unstructured data and provides a scalable, cost-effective solution. This object storage can be used to create Iceberg tables, ensuring that your data is not only stored efficiently but also organized in a way that makes it immediately accessible for analysis. This makes it incredibly simple to get your data into warehouses, lakes, or analytics engines. The best part is that the data is always fresh, accurate, and ready for you to use. The Advantage of Using Object Storage Tableflow’s seamless integration with object storage systems like Amazon S3 is one of its standout benefits. Given that object storage is specifically designed to manage vast amounts of unstructured data, it perfectly complements the large-scale data management capabilities that Tableflow offers. Whether you’re dealing with raw logs, multimedia files, or complex transactional records, object storage can handle it all with ease. By storing data in an object storage system ensures that data remains highly durable, easily accessible, and cost-effective to manage. This approach is also perfectly suited for Iceberg’s open table format, which thrives in environments where data is stored flexibly and efficiently. Stream-Table Duality A unique feature of Tableflow is something called “stream-table duality.” This means that Tableflow, with the help of Apache Iceberg, can manage data as both streams and tables. Before, you had to choose between optimizing for real-time data or batch analysis. With Tableflow, you don’t have to choose. The same data can be accessed as a live stream or a historical table, depending on what you need. Key Features of Confluent Tableflow Real-time Data Processing: Tableflow lets you process data in real-time, so you can get insights and make decisions based on the latest information. Scalability and Flexibility: It’s built to scale as your business grows, ensuring smooth performance even as your data volumes increase. Event-Driven Architecture: This makes it easy to integrate and synchronize data across different systems, improving data accessibility and consistency. Fault Tolerance and Reliability: With built-in mechanisms for data replication and recovery, Tableflow minimizes the risk of data loss or downtime. Why Tableflow is Better Than Traditional Approaches Instant Insights: Gain real-time insights to make quicker, more informed decisions without the delay of traditional processing methods. **Streamlined Architecture: **Tableflow’s event-driven design simplifies data infrastructure, reducing the complexity typical of data warehousing and lakehouse setups. Dynamic Scalability: Easily scale your data infrastructure to meet changing demands, ensuring cost-efficiency and optimal performance. Modern Technology Integration: Tableflow seamlessly connects with contemporary data technologies like Apache Kafka, enhancing its ability to integrate with diverse data sources and applications. The Future of Data Streaming Confluent Tableflow marks a significant leap forward in data streaming and processing, especially for organizations aiming to unify their operational and analytical data. By leveraging modern technologies like Apache Iceberg and object storage, Tableflow not only simplifies data pipelines but also enhances data governance, making it easier and more cost-effective to manage large-scale data environments. It bridges the often complex gap between real-time data streams and historical analytics, offering a seamless solution that optimizes both data accessibility and usability. As Confluent has noted, “The first version of Tableflow stores the data in Confluent Cloud, however, we know that being able to store long-term data in customer-owned storage is important. In the near future, Tableflow will have the option to store the Apache Iceberg metadata and parquet files directly in your own object storage.” This upcoming feature will give you even more control and flexibility over your data, allowing you to keep your long-term data exactly where you want it. Confluent Tableflow is an innovative solution that addresses many of the challenges faced by organizations dealing with large volumes of data. Its real-time processing capabilities and event-driven architecture make it a powerful tool for businesses that require timely insights and seamless data integration. The platform’s ability to scale and integrate with modern technologies like Apache Kafka further solidifies its position as a leading choice for enterprises looking to modernize their data infrastructure. By simplifying complex data workflows and enhancing data governance, Tableflow stands out as a forward-thinking solution that can transform how businesses manage and utilize their data. --- # Understanding Redpanda Connect / Benthos URL: https://platformatory.io/blog/Understanding-RedpandaConnect/ Published: 2024-09-06 Authors: Subramanya Madhyastha Categories: Redpanda, Stream Processing, Redpanda Connect Before diving into the capabilities of Redpanda Connect, it’s essential to understand its origins, particularly the acquisition and transformation of Benthos, which played a pivotal role in shaping what Redpanda Connect is today. Benthos, an open-source data streaming tool, was renowned for its versatility and simplicity in managing and processing data streams. It gained popularity due to its declarative approach, allowing users to define complex data processing pipelines with minimal configuration. Benthos was particularly favored for its stateless processing, which made it highly reliable and easy to scale. Key Features of Benthos: Declarative Configuration: Users could define processing pipelines using a simple configuration file, making it accessible even to those without deep programming expertise. Flexibility: Benthos supported a wide range of input, output, and processing components, making it adaptable to various use cases. Scalability: Built with scalability in mind, Benthos could handle high-throughput data streams efficiently. The Acquisition by Redpanda Recognizing the potential of Benthos, Redpanda, a company known for its high-performance streaming data platform, acquired Benthos. The acquisition marked the beginning of Benthos’ transformation into what is now known as Redpanda Connect. The Fork to Bento While Redpanda acquired Benthos, rebranding it as Redpanda Connect and introducing commercial licensing for key integrations. This prompted WarpStream to fork the Benthos project, renaming it Bento, which will remain a 100% MIT-licensed, open-source project. The Bento fork continues Benthos’ legacy, offering a lightweight, Go-based stream processing alternative to Kafka Connect. WarpStream invites others to contribute and help maintain Bento, ensuring stability and open governance for those concerned about Redpanda’s commercial shifts. You can find the new Bento repository here, as well as a hosted version of the original docs. For more details check out the full article on the fork from the official Warpstream website. What is Redpanda Connect Redpanda Connect builds upon the foundation laid by Benthos, enhancing its capabilities and integrating it into the broader Redpanda ecosystem. While Benthos provided a robust framework for data streaming, Redpanda, known for its high-performance streaming capabilities, took the functionality of Benthos and improved upon it in several ways: Integration with Redpanda Ecosystem: Redpanda Connect is designed to work natively with Redpanda’s broader ecosystem. This means it’s optimized for Redpanda’s distributed data platform, allowing for more seamless and efficient data streaming, transformation, and routing. Scalability: While Benthos is highly capable, Redpanda Connect is designed to handle larger volumes of data more efficiently. It leverages Redpanda’s architecture to scale up and manage high-throughput data streams in a more resilient and efficient way. Cohesion: Redpanda Connect provides a more unified and cohesive experience. By building on top of Benthos, it integrates well with Redpanda’s tools, offering streamlined workflows and management. In summary, Redpanda took Benthos’ foundation and optimized it to work specifically with Redpanda’s high-performance platform, adding better scalability, easier integration, and a more cohesive user experience. Redpanda Connect is a framework for creating declarative stream processors where a pipeline of one or more sources, an arbitrary series of processing stages, and one or more sinks can be configured in a single config Benefits of Using Redpanda Connect Real-Time Data Processing: Redpanda Connect can be used for real-time data processing. It can consume data from the specified inputs, process it using the specified processors, and then send the processed data to the specified outputs. This makes it suitable for use cases that require real-time data processing Fault Tolerance: Redpanda Connect includes mechanisms for fault tolerance, ensuring that data processing continues smoothly even in the event of failures. This includes support for distributed connectors and automatic recovery from errors. Transaction-Based Resiliency: It implements transaction-based resiliency with back pressure, ensuring at-least-once delivery without needing to persist messages during transit. Wide Range of Connectors: Redpanda Connect comes with a wide range of connectors, making it easy to integrate with your existing infrastructure. Some of the connectors include AWS DynamoDB, AWS Kinesis, Azure Blob Storage, MongoDB, Kafka, and many more. Data Agnostic: Redpanda Connect is totally data agnostic, which means it can handle any type of data you need to process. Overlap with Traditional Tools: Redpanda Connect has functionality that overlaps with integration frameworks, log aggregators, and ETL workflow engines. This means it can be used to complement these traditional data engineering tools or act as a simpler alternative. Key Components of Redpanda Connect Redpanda Connect is composed of several key components that work together to provide a robust data streaming service: Inputs: These are the sources from which data is consumed. They can be various services like Kafka, AWS S3, HTTP, etc. Buffers: These are optional components that can be used to temporarily store data before it is processed Processors: These are the components that perform operations on the data. They can perform various tasks like mapping, filtering, etc. Outputs: These are the destinations where the processed data is sent. They can be various services like AWS S3, HTTP, etc. Observability Components: These components allow you to specify how Connect exposes observability data. They include HTTP, logger, metrics, and tracing. How Does Redpanda Connect Work? Redpanda Connect works by consuming data from the specified inputs, optionally storing it in a buffer, processing it using the specified processors, and then sending the processed data to the specified outputs. The observability components provide visibility into the operation of the Connect pipeline. In this example, we’ll set up a Kafka-Benthos pipeline where data is consumed from one Kafka topic, processed by Benthos, and then sent to another Kafka topic. We’ll use Docker Compose to spin up a Zookeeper, Kafka, and Benthos services, and we’ll walk through each step of the process, including how to verify that the data has been processed correctly. Step 1: Create the Docker Compose File Let’s start by creating a docker-compose.yml file. This file defines the services we need: Zookeeper, Kafka, and Benthos. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 version: '3.7' services: zookeeper1: image: confluentinc/cp-zookeeper:7.6.2 hostname: zookeeper1 container_name: zookeeper1 ports: - "2181:2181" command: zookeeper-server-start /etc/kafka/zookeeper.properties volumes: - ./zookeeper1:/etc/kafka deploy: resources: limits: cpus: "1" memory: 512M kafka1: image: confluentinc/cp-server:7.6.2 hostname: kafka1 container_name: kafka1 depends_on: - zookeeper1 command: kafka-server-start /etc/kafka/server.properties volumes: - ./kafka1:/etc/kafka deploy: resources: limits: cpus: "1.5" memory: 1536M benthos: image: jeffail/benthos:latest hostname: benthos container_name: benthos volumes: - ./benthos.yaml:/benthos.yaml ports: - "4195:4195" depends_on: - kafka1 Step 2: Configure Benthos Next, we’ll configure Benthos by creating a benthos.yaml file. This configuration will consume messages from the benthos Kafka topic, process each message by squaring its value, and then produce the result to the destination_topic. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 input: kafka: addresses: - kafka1:19092 topics: [ benthos ] #source topic name consumer_group: benthos_group client_id: benthos_client start_from_oldest: true tls: {} sasl: {} pipeline: processors: - bloblang: | root = this * this output: kafka: addresses: - kafka1:19093 topic: destination_topic # The new topic to sink data into client_id: benthos_client tls: {} sasl: {} max_in_flight: 64 Benthos uses a powerful language called Bloblang for data transformations. Bloblang allows you to manipulate and reshape data in various ways. root = this * this: This is the specific Bloblang expression used in the processor. Let’s break it down: root: This represents the entire document or message being processed. Assigning a value to root effectively transforms the entire message. this: In Bloblang, this refers to the current value of the data being processed. If the data is a single number, this represents that number. this * this: This expression takes the value of this (i.e., the number) and multiplies it by itself. This operation squares the number. For example, if the incoming message is 2, this processor will transform it to 4. Step 3: Spin Up the Services With your docker-compose.yml and benthos.yaml files in place, you can now bring up the services using Docker Compose. 1 docker-compose up -d This command will start the Zookeeper, Kafka, and Benthos services in detached mode. Step 4: Create Kafka Topics Before sending any data, you need to create the destination Kafka topic that will be used: destination_topic. Step 5: Produce messages in the source topic and verify the output by consuming in the destination topic: Here we have produced a simple set of integers to the source topic and then consumed from the destination topic. Applications and Use Cases Data Integration: Redpanda Connect can be used to integrate data from various sources and send it to different destinations using its wide range of connectors. ETL Workflows: Redpanda Connect can be used to build ETL (Extract, Transform, Load) workflows. It can extract data from various sources, transform the data using its processors, and load the transformed data into various destinations. Data Filtering: With its processors, Redpanda Connect can be used to filter data. This can be useful in use cases that require filtering of data before it is sent to the destination. Log Aggregation: Redpanda Connect can be used to aggregate logs from various systems and send them to a centralized logging service. This can be useful for monitoring and debugging distributed systems. Comparison with Kafka Connect In the world of data streaming, both Kafka Connect and Redpanda Connect serve as critical tools, but they differ significantly in approach and design philosophy. Kafka Connect, part of the broader Apache Kafka ecosystem, is known for its robust, distributed architecture, making it ideal for complex ETL workflows and large-scale deployments. Redpanda Connect, on the other hand, evolved from the lightweight, open-source Benthos project and focuses on simplicity, stateless processing, and high performance. While Kafka Connect excels in stateful transformations, Redpanda Connect aims to streamline real-time data streaming with minimal overhead. Here’s how they stack up against each other. Category Kafka Connect Redpanda Connect Architecture Distributed, scalable, with support for standalone and distributed modes. Declarative, stateless, simpler architecture focused on ease of deployment. Ecosystem & Integration Part of the Apache Kafka ecosystem; integrates seamlessly with Kafka topics and brokers. Designed for Redpanda, with flexibility inherited from Benthos; supports a wide range of connectors. Configuration Requires detailed configuration for connectors, tasks, and workers; supports distributed configuration. Simple, declarative configuration with minimal setup effort, focusing on lightweight pipeline setups. Processing Stateful processing with distributed transformations; suitable for complex ETL workflows. Stateless, lightweight processing with simpler use cases; focuses on chained, minimal transformations. Observability Extensive monitoring through JMX, REST APIs, and integration with systems like Prometheus. Offers observability components like logging and tracing, but with potentially less mature tooling. Licensing & Community Open-source under Apache License 2.0, with strong community and extensive library of connectors. Mixed licensing post-acquisition; originally fully open-source, now some parts are proprietary, leading to a fork. Use Cases Ideal for large-scale, complex ETL workflows, distributed fault tolerance, and enterprise-level deployments. Best for simpler, stateless streaming, and performance-sensitive applications with minimal overhead. Performance & Scalability Scales effectively with Kafka's architecture; handles high-throughput data and large deployments. Designed for low-latency streaming; excels in performance but may not scale as easily for large, stateful use cases. This comparison highlights the core differences and strengths of both tools based on their architecture, processing capabilities, and ecosystem. Getting Started with Redpanda Connect To get started with Redpanda Connect, you can follow the Getting Started guide. This guide will walk you through the process of setting up Redpanda Connect and using it for your data streaming needs. Conclusion Redpanda Connect stands out as a powerful and versatile tool in the realm of data streaming. With its declarative configuration, fault tolerance, and wide range of connectors, it simplifies the complexities of real-time data processing across various systems. Its flexibility and scalability make it a valuable asset for diverse use cases, from ETL workflows to log aggregation. As you delve into Redpanda Connect, you’ll discover a reliable and efficient solution that meets the demands of modern data engineering, providing both the power and ease of use required to handle large-scale data streams effectively. --- # Exploring Kafka UI Solutions: Features, Comparisons, and Use Cases URL: https://platformatory.io/blog/comparision-of-kafka-ui-monitoring-tools/ Published: 2024-09-05 Authors: Zeenia Gupta Categories: Kafka, Observability, Kafka Operations Introduction This blog post explores various UI solutions available for Apache Kafka. Why do we need a Kafka UI when we have well documented APIs and client libraries? There are a lot of reasons. We get a more comprehensive and visual overview of what’s happening in our clusters, a.k.a big picture. It is easier to troubleshoot and diagnose problems. Imagine yourself looking out for messages from a topic and getting nothing but crickets. Did you configure the options correctly? Do you even have RBAC to consume from that topic? These are some of the things you can avoid in the first place when using a UI. Better administration. A good UI helps organizations and teams manage their data, users and infrastructure with improved operational efficiency. What are the criteria to look out for in a good UI? There isn’t an agreed-upon list, but we’ve compiled one to the best of our abilities. Data management. This entails browsing of messages (including live tailing), configuring topics and partitions and message serialization. User management. Authentication and authorization. Brownie points for quota management. Management of multiple clusters. Can the UI act as a single pane of glass for managing multiple clusters? Kafka streams integration. Can we visualize stream topologies? KSQL integration. Can we run KSQL queries via the UI? Kafka connect integration. Can we integrate with external systems via Kafka connect in the UI? Metrics. Can we visualize key metrics? Not all of these criteria are compulsory for evaluating a UI. In fact, some UI solutions brand themselves to only certain items in this list, and that’s fine. In other words, this isn’t a “be all end all” laundry list and your mileage may vary depending upon what you are on the lookout for. Also, you can use a combination of different tools for different things if you have the ability to do so. For instance, it is not uncommon to use Confluent control center to visualize topics and manage them and use Grafana + Prometheus to visualize cluster metrics. Now that we’ve laid down the need for a UI and the criteria to evaluate them, let’s do a deep dive of each one in no particular order. Comparison of UI Tools Confluent Control Center The Confluent Control Center, also known as C3, is a part of Confluent’s enterprise offering. You are free to try it on a local setup as documented here. C3 allows you to, Manage multiple Kafka clusters from the UI. Although you cannot add/provision new clusters via the UI. Here’s an example of multi-cluster configuration in C3. Manage topics, create new topics, browse/tail messages in topics. Configure and manage schema for topics if C3 is configured with Schema registry. Supports JSON, Avro and Protobuf formats. Manage RBAC roles and role assignments via the UI. View and manage kafka stream apps(including topology, stream lineage), KSQLDB queries(editor and flow screen) and Kafka connectors via the UI. C3 has provision to view basic topic related metrics like production and consumption bytes(throughput), under replicated partitions, out of sync replicas(availability) and consumer lag. There is also a provision to configure alerts via the UI. For example, you can set up an alert where if the cluster is down, a notification will be sent to slack/email/Pagerduty. Pros Comprehensive UI, arguably the only UI which supports Kafka streams, KSQL and multi cluster management. Provides detailed monitoring and visualization of Kafka brokers, topics, consumers, and producers. We can monitor multiple kafka clusters from a single interface, which is useful for organizations running complex applications. Cons Comes as part of the Confluent enterprise offering. Can’t be used standalone. The UI is designed for a specific set of features, it may lack the flexibility for some organizations whose requirements are for custom monitoring. It can be resource intensive, as the control center also requires a significant CPU, memory, and storage. Conduktor To be fair, Conduktor is more of a suite of tools catered for different audiences rather than a single application. For starters, there’s the Conduktor Desktop which is a downloadable desktop application. It has the ability to connect to any Apache Kafka cluster, a powerful visual UI to browse data in topics, works with all data serialization formats and any Kafka security setup. It also ships with 2 Kafka demo clusters to get a feel of the product. We can use Conduktor to manage Kafka streams applications(with limited visualization of topology) and run KSQLDB queries. Higher tiers offer features like, Standards enforcement when creating topics Audit logs traceable down to individual messages and users. SSO An interesting USP not found elsewhere is the data masking feature. It helps cluster admins create policies which mask PII (Personally Identifiable Information) to comply with various Conduktor allows you to: With the RBAC model, you can manage user and group access. Also allows administrators to grant operation access. Integrate with your existing identity provider (IdP). Can view ACLs as service accounts. Supports advanced javaScript filters for segmenting messages with specific criteria which provides optimization for end users that need to navigate their kafka data seamlessly. Pros Conduktor can be used as a standalone tool without requiring additional components which simplifies deployment and integration. Provides deep integration to your data service provider, which gives you flexibility to manage your kafka infrastructure from one central platform. Offers several user authentication options, including local users, an LDAP server, LDAPS, Auth0, Okta, Keycloack, and Azure. Cons Although, the monitoring provided by Coduktor is really good. However, it lacks tracing which is a very important component that needs to be considered a monitoring platform. Kpow Kpow by Factor House is a Web UI for Apache Kafka which allows us to monitor a cluster, viewing topics, managing consumer groups, produce and consumer data with integration into the Schema Registry. Kpow Features include Real - time monitoring: of kafka brokers, topics, partitions, and consumer groups in real - time. Browsing and searching: through messages in Kafka topics, which make it easy for developers to inspect and debug the data flows within the cluster Schema Registry integration: Users can manage and validate the schema registry directly through Kpos interface. Makes topic search easy with built - in support for JSON Query (JQ) predicates. Alerting System:Set up the alerts for kafka metrics and events, so the team can respond quickly to critical issues. Editions Kpow Community Edition (CE): Free for organizations to install in up to three non-production environments. Team: Packed with CE features and enterprise integrations with standard support. Enterprise Version: Offers additional features such as enterprise support, Java 8 compatibility, dedicated account manager and more. Pros Ensure authentication and authorization while aligning Kafka operations with organizational policies, specifically designed to meet enterprise requirements. Can be deployed in various environments, including on - premises and cloud - based setups. The Kpow CE supports multiple Kafka clusters including Confluent Cloud, AWS MSK, Redpanda, etc. Multi - topic search in JQ filtering, which allows us to reduce time to find the resolution of production issues and work more efficiently in general system development. It’s like find the needle in a haystack in record time. Cons We didn’t have access control such as RBAC or any authentication in Community edition. We need to buy the paid editions such as Team and Enterprise Version, which can be very expensive for smaller organizations. During the topic data inspection, if no key and/or value deserializer is provided, the output shows those fields as null, making it difficult to determine why values are missing. AKHQ AKHQ previously known as Kafka HQ, enables developers to search and explore the data within the kafka cluster in a unified console. It offers features for managing topics, topic’s data, consumer groups, schema registry, Kafka connect and more. AKHQ is highly configurable, allowing you to add authentication and roles to the application when using it within an organization, or we can remove it when running it in Docker, Kubernetes, or as a Standalone application. Pros Supports Avro, and is compatible with LDAP and RBAC. It provides various useful features such as multi - cluster management, message browsing, live tailing, authentication, authorization, read - only mode, schema registry, and Kafka connect management. Supports AWS Identity and Access Management (IAM) Access Control for Amazon MSK. Open source with an active and engaged community. Cons Provides partial support for Protobuf schema registry, as it only supports protobuf deserializer. Lacks support for Replica Change, JMX metrics visualization and charts. Does not support alerting. May not integrate seamlessly with other kafka components such as external monitoring tools. LIkely require additional configuration or custom development. Cruise Control Cruise Control is an open source project which helps to run Apache Kafka clusters at large scale. It is designed to address the operation scalability issues. It optimizes the distribution of workloads within Kafka to enhance performance and overall cluster health. Cruise control is used within LinkedIn to manage almost 3000 Kafka brokers. Key features of Cruise Control Track resource utilization for brokers, topics, and partitions. Generate multi - goal rebalance proposals. Rebalances partition topology, newly added brokers, and facilitates broker removal. Pros Automatically balance the workload across kafka brokers, ensuring even distribution of partitions. Optimize the resource usage by distributing partitions based on broker load. Provides the metrics to monitor the performance of Kafka cluster, which helps in detecting and troubleshooting the issues proactively. Cons Setting up and configuring the Cruise Control can be complex involving numerous configuration parameters such as metrics reporter, configuring rebalancing strategies, and defining optimization goals. Despite the automation such as detecting anomalies, rebalancing partitions, and optimizing resource usage. It often requires manual intervention to adjust settings, correct issues, and scenarios due to its complex configurations. The Varied settings can be challenging and require careful analysis, and ongoing monitoring and adjustments to suit your workloads. There is no in - built alerting, requiring external tool to set up the alerts based on the cruise control metrics Redpanda Console Redpanda Console(previously known as KOwl) is a web application designed to help developers to explore messages in your Apache kafka clusters and gain better insight into the kafka clusters. It is solely developed and maintained by Redpanda, with restrictive commercial support from other vendors due to BSL license agreement. Redpanda Console Feature Include Message Viewer: Explore topic messages in the message viewer through ad - hoc queries and dynamic filters. You can find any message you want using JavaScript functions filter. Consumer groups: List all consumer groups along with their active group offsets. Topic Overview: Browse the list of kafka topics, review their configuration, space usage, list all consumers. Security: Create, list, or edit Kafka ACLs and SASL - SCRAM users. Pros Includes the Schema Registry in its binary, which allows it to run immediately with the default configuration. It supports both Avro and Protobuf serialization formats, as well as Protobuf message deserialization into JSON format. Through UI, you may perform a variety of cluster administration tasks, carry out mulit cluster management, view brokers, vew and create topics, examine consumer group data, configure listeners, set up ACLs, manage nodes, and more. It easily integrates with Prometheus to provide monitoring and alerting system. Cons Redpanda doesn’t support setting request quotas or triggering partition rebalancing through the UI. Data must be written to disk synchronously, otherwise, it is possible to lost data during an election of a new leader. Kafka-ui UI for Apache Kafkais an open - source web service that allows developers to monitor and manage Apache Kafka cluster. With Kafka - ui , developers can track data flows, find and troubleshoot issues faster and ensure optimal performance. The dashboard includes the key metrics of your kafka cluster, including Brokers, topics, partitions, production, and consumption. Pros Centralized monitoring and management of all Kafka cluster in one place. Ability to browse messages with JSON, plain text, and AVRO encoding Support creating new topics with dynamic configuration. Custom serialization/deserialization plugins are available for the data such as AWS Glue. Cons Kafka UI lacks an integrated alerting system, which requires developers to rely on external tools for alerts. Offers fewer security features compared to enterprise tools such as it offers only basic support for role-based access control (RBAC), which is one of the authorization mechanisms. For authentication, you must configure each OAuth 2.0 provider manually. It lacks maintenance features like adding brokers, increasing partitions, rebalancing, and replica changes. 7 Monitoring Tools for Apache Kafka Clusters A quick comparison of the Apache Kafka cluster monitoring tools Confluent CC Conduktor Kpow(CE) AKHQ Cruise Control Redpanda Console Kafka - ui Multi-Cluster Management Yes No No Yes No No Yes Message Browsing Yes Yes Yes Yes No Yes Yes Protobuf Support Yes Yes Yes Partial No Yes Yes Avro Support Yes Yes Yes Yes No Yes Yes Amazon MSK IAM Support No Yes Yes Yes No Yes Yes JMX Metrics Validations Yes Yes No No Yes Yes Yes Schema Registry Yes Yes Yes Yes No Yes Yes KSQL Integration Yes Yes No Yes No No Yes Authentication Yes Yes No Yes No Paid Yes Authorization Yes Yes No Yes No Paid Yes Resource Usage Yes No No No Yes No No Rebalancing No Yes No No Yes No No Conclusion Having the right UI tools for monitoring and managing Apache Kafka clusters is crucial for maintaining cluster health. A user-friendly interface allows you to easily observe data flows, track metrics, and troubleshoot issues without relying on multiple CLI tools. This streamlined approach leads to fewer bottlenecks, faster reporting, and more cost-effective development. In this article, I have provided an overview of the leading UI tools for Kafka cluster management and monitoring. While I strive to be objective, I’m sure the community will have additional insights to contribute. Personally, I prefer Confluent Control Center because it offers a wide range of in-built features, such as KSQL, Kafka Connect, and many more. It also allows us to manage more than one cluster, provides detailed information about the Kafka Cluster, and enables us to configure ACL and RBAC directly from the UI. Additionally, it supports private networking between the AWS VPC and the Confluent Cloud kafka cluster. --- # Operational DB Migrations with Zero Downtime URL: https://platformatory.io/blog/Operational-db-Migration-Zero-Downtime/ Published: 2024-09-05 Authors: Raghavendran Nehru Categories: Migration, CDC, Kafka Connect, Debezium, Kafka Introduction At Platformatory, we constantly work with customers whose operations demand round-the-clock availability and it is importat to maintain uninterrupted database access. They typically tend to scale their infrastructure, adopt new database technology, or making a strategic move to the cloud. So, ensuring zero downtime during database migration is critical. For our customers (or for that matter anyone), downtime isn’t just an inconvenience—it could mean lost revenue, frustrated clients, and potential disruptions that ripple across their systems. In environments where even a minor outage could impact customer experiences or critical operations, ensuring seamless database migration becomes a key priority. A carefully planned zero-downtime migration allows them to evolve and scale your infrastructure while ensuring that the services remain fully operational. Leveraging real-time data streaming and advanced synchronization techniques, our team ensures that data is continuously available while migrating databases behind the scenes. It’s about maintaining trust, keeping operations smooth, and continuing to deliver value to our clients without a hiccup. This post goes into the details of how such migrations can be orchestrated for a smooth transition by working through an example of migrating from SQL Server to MySQL (but, it can be done generically between two databases). Migrating SQL Server Database to MySQL via Kafka Connect using Debezium Let us quickly lay out the components that we will use for this. Apache Kafka is a distributed streaming platform used for building real-time data pipelines and streaming applications, enabling high-throughput, fault-tolerant data streams. Kafka Connect extends Kafka’s capabilities by integrating various data sources and sinks (destinations), while Debezium captures real-time database changes (CDC) and uses Single Message Transformations (SMT) to modify the streamed data before delivering it to Kafka topics. --- config: look: handDrawn layout: elk --- flowchart LR subgraph SQLServer["SQL Server Database"] T1("Table: Customers") T2("Table: Orders") end subgraph MYSQL["MySQL Database"] TTGT1("Table: Customers") TTGT2("Table: Orders") end subgraph KCW1["Connect Worker Running Debezium"] TW1("Source Task 1 | Transform") TW2("Source Task 2 | Transform") end subgraph KCW2["Connect Worker Running Debezium"] TWSYNC1("Sink Task 1 | Transform") TWSYNC2("Sink Task 2 | Transform") end subgraph KafkaConnect1["Kafka Connect Cluster"] FB1 end subgraph KafkaConnect2["Kafka Connect Cluster"] FB2 end subgraph FB1["w"] KCW1 end subgraph FB2["w"] KCW2 end subgraph K1["Kafka Cluster"] TP1["Kafka Topic: sqlserver.inventory_db.dbo.customers"] TP2["Kafka Topic: sqlserver.sales_db.dbo.orders"] end T1 --> TW1 --> TP1 --> TWSYNC1 --> TTGT1 T2 --> TW2 --> TP2 --> TWSYNC2 --> TTGT2 %% Styling classDef default font-size:20px,stroke:#333,stroke-width:1px,fill:#f5f5f5; classDef largeFont font-size:18px; classDef kafkaStyle fill:#e0f7e9,stroke:#4caf50,stroke-width:1px; class K1,K2 kafkaStyle; %% Apply the largeFont class to subgraph titles class SQLServer,MYSQL,KCW1,KCW2,KafkaConnect1,KafkaConnect2,K1 largeFont; Key Components: Kafka Topics: Each table from SQL Server streams data to a corresponding Kafka topic. Kafka Connect (Debezium): Captures the CDC events from SQL Server and pushes them into Kafka topics. Schema Registry: Ensures that data conforms to the defined schema before reaching MySQL. SMT (Single Message Transformations): Applied to transform the data (e.g., schema modifications, field renaming) before writing to MySQL. MySQL Sink Connector: Reads from Kafka topics and writes the transformed data into the MySQL database. Detailed Migration Process 1. Initial Setup Set Up the Target MySQL Database Create the schema and tables in the target MySQL database to mirror the source SQL Server databases. Ensure the target schema is flexible to support the changes you’ll apply using SMT. Deploy Kafka and Kafka Connect Set up a Kafka cluster and deploy Kafka Connect. Kafka will be used to stream data from SQL Server databases to the target MySQL databases. Install the Debezium SQL Server Connector in Kafka Connect for CDC from SQL Server. Set up the Kafka Schema Registry to ensure the data schemas are enforced during transmission. 2. Configure Debezium for CDC Debezium Connectors For each SQL Server database, configure a Debezium connector to track changes (CDC). The connector will capture all insert, update, and delete operations in real-time from the transaction log of SQL Server databases and publish them to Kafka topics. Example configuration for one database: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 { "name": "sql-server-connector", "config": { "connector.class": "io.debezium.connector.sqlserver.SqlServerConnector", "database.hostname": "", "database.port": "1433", "database.user": "", "database.password": "", "database.dbname": "", "database.server.name": "sql-server-source", "table.include.list": "schema.table", "snapshot.mode": "initial", "database.history.kafka.bootstrap.servers": "", "database.history.kafka.topic": "dbhistory.sqlserver", "transforms": "unwrap", "transforms.unwrap.type": "io.debezium.transforms.UnwrapFromEnvelope", "transforms.unwrap.drop.tombstones": "false" } } Kafka Topics Each SQL Server table will stream changes into separate Kafka topics. Kafka will act as the intermediary, ensuring that any change in the source databases is streamed in real-time to the target. 3. Applying Schema and Single Message Transformations (SMT) Configure Schema Registry Use Kafka Schema Registry to enforce schemas for each table. This ensures that the data adheres to the expected format during the migration. Avro/JSON schema for the records will be managed through the registry. Apply SMT for Data Transformation Use Kafka Single Message Transformations (SMT) to modify the records before they are written to MySQL. For example, you might want to rename fields, mask sensitive data, or change data types. Example SMT configuration: 1 2 3 4 5 6 { "transforms": "InsertField", "transforms.InsertField.type": "org.apache.kafka.connect.transforms.InsertField$Value", "transforms.InsertField.static.field": "db_migrated", "transforms.InsertField.static.value": "true" } Define Target Schema in MySQL The transformed records will fit into the target schema in MySQL. You can define specific rules in SMT to adjust field names or schemas as per the new structure. 4. Continuous Sync with Zero Downtime Load Data Initial Bulk Load Perform an initial bulk load of the data from SQL Server to MySQL using SQL tools or custom scripts to ensure the target database starts with a full copy of the data. Incremental Data Load Our preferred alternative to build load is a feature in Debezium called Incremental Snapshots with CDC. This is particularly useful for large tables or databases where a full snapshot is impractical due to size or operational constraints. Debezium’s incremental snapshot feature enables the connector to: Capture data in smaller chunks. Continue capturing CDC events while the snapshot is being taken. Recover from failures and resume the snapshot from where it left off. Benefits of Using Incremental Snapshots: Performance: Incremental snapshots reduce the overhead of taking a complete snapshot, especially for large datasets. The system captures data in chunks while streaming CDC events in parallel. Fault Tolerance: In case of errors during the snapshot process, Debezium can resume the snapshot without starting over. Reduced Load on the Source Database: By capturing data in smaller chunks, the load on the source database is minimized, and locks are held for shorter durations. How to Configure Debezium for Incremental Snapshot and CDC Below is a Debezium SQL Server Source Connector configuration that enables incremental snapshots along with CDC. Configuration Example for Incremental Snapshot: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 { "name": "sql-server-connector", "config": { "connector.class": "io.debezium.connector.sqlserver.SqlServerConnector", // SQL Server connector "database.hostname": "your-sqlserver-hostname", // SQL Server host "database.port": "1433", // SQL Server port (default: 1433) "database.user": "your-username", // SQL Server username "database.password": "your-password", // SQL Server password "database.server.name": "sqlserver-source", // Logical server name "database.dbname": "your-database-name", // Name of the SQL Server database "database.history.kafka.bootstrap.servers": "your-kafka-brokers", // Kafka brokers for schema history "database.history.kafka.topic": "schema-changes.sqlserver", // Kafka topic for schema changes "table.include.list": "dbo.customers,dbo.orders", // List of tables for CDC and snapshot // Configure initial snapshot and CDC "snapshot.mode": "initial", // Take an initial snapshot (can be "initial" or "initial_only") // Enabling incremental snapshot "snapshot.fetch.size": "1000", // Fetch size for incremental snapshots (number of rows per batch) // Incremental snapshot configuration "incremental.snapshot.enabled": "true", // Enable incremental snapshot "incremental.snapshot.chunk.size": "5000", // Size of the chunks for incremental snapshot (rows per chunk) // CDC (Change Data Capture) settings "database.encrypt": "false", // Disable encryption "database.tcpKeepAlive": "true", // Keep TCP connection alive // Kafka schema configuration "include.schema.changes": "true", // Include schema change events in Kafka topics "transforms": "unwrap,AddField", // Apply transformations "transforms.unwrap.type": "io.debezium.transforms.UnwrapFromEnvelope", // Unwrap Debezium message envelope "transforms.unwrap.drop.tombstones": "false", // Drop tombstone messages "transforms.AddField.type": "org.apache.kafka.connect.transforms.InsertField$Value", "transforms.AddField.static.field": "source_database", "transforms.AddField.static.value": "${database.name}" } } How Incremental Snapshot Works in Combination with CDC: Initial Snapshot: Debezium starts by taking an incremental snapshot of the specified tables. Instead of taking a full snapshot in one go, it splits the data into smaller chunks (e.g., 5000 rows per chunk). This makes the snapshot process more efficient and minimizes the load on the source database. CDC in Parallel: While the snapshot is being taken, Debezium continues to monitor the transaction log for any changes. These CDC events are captured in real-time and sent to Kafka topics. This ensures that no changes are missed during the snapshot process. Recovery from Failures: If an error occurs during the snapshot, Debezium can resume from where it left off, instead of starting the snapshot from scratch. This is particularly important for large datasets, where a full snapshot could take a long time. Post-Snapshot: After the incremental snapshot is complete, Debezium continues to monitor CDC events only, as the snapshot has already captured the full historical data. After this step, begin the real-time synchronization using Debezium. Start Streaming CDC Data Kafka Connect with Debezium will start streaming the changes from the SQL Server databases to Kafka topics. The transformed records, as per the SMT rules, will be written into the MySQL database in real-time, ensuring that the two databases stay in sync. Validation Continuously validate the data in MySQL to ensure consistency with the source SQL Server databases during the migration process. 5. Switchover to MySQL Monitor and Verify Monitor the Kafka topics and connectors to ensure that any new changes in the source SQL Server databases are successfully replicated to MySQL. Debezium Monitoring with Prometheus: Debezium provides out-of-the-box metrics for monitoring the health of the CDC process. Metrics: debezium_task_state: The state of the Debezium tasks. debezium_task_errors: Number of errors encountered. debezium_task_latency: The latency of CDC events. Dashboard: Use Prometheus and Grafana to monitor Debezium’s task status, error rates, and event latency. Data Integrity and Consistency Metrics Some of the most important metrics to track to ensure that data integrity and consistency are maintained during the migration process: Row Count Comparison: What it Measures: Compares the number of rows in each table in the source database and the target database after migration. Why it’s Important: A mismatch in row counts indicates that some records may not have been migrated, or duplicates may have been introduced. This is a basic but crucial integrity check. How to Monitor: Run Periodic Queries: Count the number of rows in critical tables in both the source and target databases, and compare the results. Dashboards: Display row count differences for each table, along with alerts for discrepancies. Checksums or Hash Values: What it Measures: Uses cryptographic hashes or checksums to ensure that the actual data values (not just row counts) are identical between the source and target databases. Why it’s Important: Even if row counts match, the actual data within those rows may differ due to data corruption, truncation, or transformation issues. How to Monitor: Hash Functions: Calculate a hash or checksum for key columns (or entire rows) in both the source and target databases. Comparison Logic: Compare the hash values between the two databases to detect any discrepancies. Dashboards: Show real-time comparison results, flagging any mismatches between source and target hashes. Cutover Without Downtime Once the target MySQL database is in sync and you’ve confirmed that all data has been migrated successfully, you can switch the application(s) to point to the MySQL database. In case there are microservices that write to the database, having a Blue/Green deployment with new database configuration will help in migration. In case Blue/Green deployment is not adopted, then a gradual rollout would be able to achieve the same. Kafka will continue streaming changes during the switchover, ensuring zero downtime. Conclusion By leveraging Kafka, Debezium, Kafka Connect, SMT, and Schema Registry, you can achieve zero-downtime migration of 100 SQL Server databases to MySQL. This approach ensures that both systems remain in sync during the migration process while applying transformations to fit the new schema in MySQL. --- # How to migrate Kafka clusters without downtime URL: https://platformatory.io/blog/How-to-migrate-kafka-clusters-without-downtime/ Published: 2024-09-05 Authors: Subramanya Madhyastha Categories: Kafka, Migration, Kafka Operations Migrating Kafka clusters can be a daunting task, especially when minimizing downtime is a priority. However, with careful planning and the right tools, it’s possible to execute a seamless migration. This guide will walk you through the process step by step, ensuring a smooth transition to your new Kafka environment. Understand the Reasons for Migration Before diving into the migration process, it’s essential to understand why you’re migrating. Common reasons include: Upgrading to a newer Kafka version or a managed service (e.g., Confluent Cloud, AWS MSK). Rearchitecting the cluster to improve performance, scalability, or fault tolerance. Moving to a new environment, such as transitioning from on-premises to the cloud. Organizations might have a specific need for migrating other than these mentioned reasons. Knowing the motivation behind your migration will guide your planning and help you make informed decisions throughout the process. Plan Your Migration Strategy A successful migration starts with a solid plan. Key factors to consider include: Cluster Configuration: Document the current Kafka cluster’s configuration, including topics, partitions, replication factors, and consumer groups. Decide if you’ll replicate the existing setup or make improvements. Data Migration: Determine how you’ll move data from the old cluster to the new one. Consider using tools like Apache Kafka’s MirrorMaker 2 or Confluent Replicator, which can synchronize data between clusters. Consumer Offset Management: Plan how to manage consumer offsets to ensure that your consumers resume processing at the correct point in the new cluster. Downtime Tolerance: Assess your application’s tolerance for downtime. The goal is to minimize it, but understanding the acceptable limits will help in planning. Define Migration Scope Assess Your Existing Cluster A thorough understanding of your existing Kafka cluster deployment is essential for ensuring a smooth transition to the new Kafka environment. This assessment should include: Cluster Configurations: Review the current configurations of your Kafka cluster to understand how they might need to change in the new environment. Topic Topology and Data Model: Analyze the structure of your topics, partitions, and data flow to ensure compatibility and performance in the new cluster. Kafka Client Configurations and Performance: Evaluate how your Kafka clients are configured and their performance metrics. Understanding these will help in replicating or improving them in the new setup. Benchmarking: Identify key benchmarks that can be used to validate the performance and functionality of workloads once they are migrated to the new cluster. This includes assessing latency requirements and understanding how latency is measured, so you can effectively evaluate it during benchmarking in the new environment. Dependency Planning: Consider all applications that connect to your existing Kafka cluster and understand how they depend on each other. This ensures that all relevant applications are targeted during the migration, and necessary changes are made. Determine Data Replication Requirements Kafka migrations can generally be categorized into two scenarios: migrating without data and migrating with data. Each scenario requires different approaches and considerations. Migrating Without Data Migration In cases where you are not required to move existing data, the migration process focuses on shifting producers and consumers to a new Kafka cluster without interrupting the data flow. Steps for Migration Without Data: Prepare the New Cluster: Set up the new Kafka cluster with configurations that match or exceed the capabilities of the existing cluster. Ensure the new cluster is fully tested in a non-production environment to avoid unexpected issues during the actual migration. Dual Writing (Shadowing): Implement dual writing, where producers send data to both the old and new clusters simultaneously. This ensures that the new cluster starts receiving data without disrupting the current flow. Gradually increase the load on the new cluster while monitoring its performance. Consumer Migration: Start migrating consumers to the new cluster in phases. Begin with less critical consumers and verify that they are processing data correctly. Ensure that consumers can handle data from the new cluster without issues such as reprocessing or data loss. More information on this will follow. Cutover: Once the stability of the new Kafka cluster is confirmed and the consumers have already been migrated, the next step is to stop dual writes from the producer. At this point, the producer should only write to the new cluster. This ensures a smooth transition while maintaining data consistency and minimizing any potential risks associated with the migration. Make sure a rollback plan is in place to handle any unforeseen issues during this process in case the cutover is unsuccessful. This plan should allow you to revert to the original cluster quickly to minimize downtime and data loss, ensuring business continuity while troubleshooting any issues with the migration. Monitor both clusters during and after the cutover to ensure everything is functioning as expected. Decommission the Old Cluster: After a period of stable operation on the new cluster, decommission the old cluster. Ensure all relevant data and metadata have been successfully transitioned before doing so. Key Considerations: Synchronization: Keep producers writing to both clusters until you are certain the new cluster can handle the full load. Monitoring: Use tools like Prometheus and Grafana to monitor the performance of both clusters during the transition. Migrating With Data Migration Data migration adds complexity, as it involves transferring not only active producers and consumers but also the historical data stored in the Kafka topics. Options for Data Migration: Cluster Linking (Confluent): Cluster Linking is a feature that enables real-time replication between Kafka clusters, allowing data to flow from the source cluster to the target cluster. Advantages: Low-latency data replication: Enables near real-time data synchronization between clusters. No offset translation required: Consumers on the target cluster can continue from the same offsets as the source. Minimal data loss: Ideal for scenarios where high data consistency is critical. Shortcomings: Schema compatibility: You’ll need to ensure schema consistency if using schema registries across clusters. Limited transformation capabilities: Focuses on pure data replication without offering complex filtering or transformation. When to use: Cluster Linking is ideal for scenarios where you need seamless, low-latency data replication with minimal data transformation. It’s the go-to choice for Confluent users looking for operational simplicity without requiring offset translation. MirrorMaker 2 (MM2): MM2 is an open-source Kafka tool for replicating data between clusters, offering more flexibility for non-Confluent environments. Advantages: Flexibility in deployment: Works well with both open-source Kafka and Confluent deployments. Supports offset translation: It provides offset translation for consumer groups across clusters. Shortcomings: Higher complexity: Offset translation may introduce complexities during migration. Potential replication lag: MirrorMaker 2 may experience higher replication lag compared to Cluster Linking, depending on configurations. Limited schema translation: If using schema registries, it lacks advanced schema translation features. When to use: MM2 is suited for environments where you require flexibility with Kafka distributions or do not mind offset translation between clusters. Confluent Replicator: A robust tool that enables data replication with advanced features like filtering, transformation, and schema management. Advantages: Filtering and transformation: Allows data filtering and transformation during replication, making it more adaptable for complex use cases. Schema management: Supports schema translation, making it ideal for enterprises where schema consistency across clusters is critical. Shortcomings: Offset translation issues: Offset translation is not automatic, requiring careful configuration. More resource-intensive: Replicator requires more resources and careful tuning compared to simpler replication methods like Cluster Linking. When to use: Choose Confluent Replicator for enterprise-grade migrations that require granular control over data replication, including filtering and schema translation. Common Steps for Migration with Data Replication Start Replication: Set up replication between the source and target clusters using one of the tools mentioned (Cluster Linking, MirrorMaker 2, or Confluent Replicator). Migrate Consumers: After verifying that data replication is working correctly, migrate consumers to the target cluster. Ensure that consumers are configured to process from the appropriate offsets (translated if necessary) based on the replication tool used. Cutover Producers: Once the consumers are stable on the new cluster, stop dual writing and switch the producer to only write to the new cluster. 4 Monitor and Validate: Continuously monitor data flow, replication consistency, and consumer performance to ensure a smooth migration. Key Considerations: Data Integrity: Ensure that data is accurately replicated without loss or duplication. Use checksums or hashing to verify data consistency. Replication Lag: Monitor and minimize replication lag to prevent data inconsistencies between clusters. Cutover Strategy: Plan the cutover carefully to avoid service disruptions. It’s often best to perform the final switch during a maintenance window. Evaluate Workload Optimization A migration is a great time to tackle some of the technical debt that may have built up in your existing deployment, such as optimizing and improving the clients, workload, data model, data quality, and cluster topology. Each option will vary in complexity. Additionally, migration provides a chance to consolidate Kafka topics by renaming or removing unused ones, which helps clean up the environment and improve data flow efficiency. This is also a good opportunity to update your security strategy. Consider enabling Role-Based Access Control (RBAC) for better user management or changing the authentication type to a more secure method. These steps will fortify the system’s security while ensuring compliance with best practices. Defining Acceptable Downtime When migrating Kafka clusters, it’s crucial to determine the amount of downtime that is acceptable for your clients. During any Kafka migration, clients need to be restarted to connect to the new bootstrap servers and apply any new security configurations specific to the destination cluster. Therefore, you must either plan for the downtime incurred when clients restart or implement a blue/green deployment strategy to achieve zero downtime. Depending on the client architecture and migration strategy, downtime can be very brief but is almost always greater than zero when the same set of clients is assigned to the new Kafka cluster. It is recommended to schedule the migration for production workloads during a maintenance window or a period of low traffic, such as nighttime or weekends. Client downtime can be categorized into two types: Downtime for writes Downtime for reads Typically, downtime for reads is more tolerable than downtime for writes, since consumers can often restart from where they left off after migrating to the new Kafka cluster and quickly catch up. The amount of client downtime will depend on the following factors: Speed of Updating Client Configurations: The time it takes to update the client bootstrap servers and security configurations. Automating this process can significantly reduce downtime. To automate the updating of client configurations and minimize downtime, consider the following strategies and resources: Use Ansible Playbooks: Automate configuration updates using Ansible, which allows for both rolling and parallel deployment strategies. Rolling deployments are safer as they update one node at a time, ensuring high availability. Refer Update a Running Confluent Platform Configuration using Ansible Playbooks Controlled Shutdown: Enable controlled shutdown (controlled.shutdown.enable=true) to gracefully stop brokers, syncing logs and migrating partitions before shutdown. This minimizes downtime during updates. Refer Best Practices for Kafka Production Deployments in Confluent Platform Client Quotas: Use client quotas to manage resource consumption effectively. This can help prevent any single client from overwhelming the system during configuration updates. Refer Multi-tenancy and Client Quotas on Confluent Cloud By implementing these strategies, you can effectively automate client configuration updates while minimizing downtime. Client Startup Time: Clients have varying startup times depending on their implementation. Additionally, specific client dependencies may dictate the order in which clients can start, potentially extending the time taken to fully restart the system. Execution Speed of Migration-Specific Steps: Any other migration-specific steps that need to be completed before restarting the clients with the new Kafka cluster can also contribute to downtime. Define Processing Requirements It is essential to clearly define the data processing requirements for each client before initiating a Kafka migration. Understanding whether clients can tolerate duplicates or missed messages will guide you in selecting the appropriate data replication tool and client migration strategy. Can Tolerate Duplicates but Not Missed Messages: Data is Migrated: Start by cutting over the consumer first, ensuring that auto.offset.reset is set to earliest. This setting ensures that the consumer processes all messages from the new Kafka cluster starting from the earliest offset, potentially causing duplicates but preventing any missed messages. Once the consumer has been transitioned, cut over the producer to begin writing to the new cluster. Data is Not Migrated: Start by enabling a dual-write setup for the producer, meaning the producer writes to both the old and new Kafka clusters simultaneously. After ensuring the dual write is functioning, cut over the consumer with auto.offset.reset set to earliest, allowing it to consume from the new cluster without missing any messages. Finally, stop producing to the old Kafka cluster once the transition is stable. Can Tolerate Missed Messages but Not Duplicates: Data is Migrated: Start by cutting over the consumer first, with auto.offset.reset set to latest. This ensures that the consumer will only process new messages from the latest offset on the new Kafka cluster, avoiding duplicates. After this, transition the producer to the new cluster to continue data production. Data is Not Migrated: Cut over the producer first to begin sending data to the new Kafka cluster. Then, transition the consumer with auto.offset.reset set to latest to process only the most recent messages on the new cluster, ensuring no duplicates. Alternatively, both the producer and the consumer can be cut over simultaneously, minimizing potential downtime. Cannot Process Duplicates or Missed Messages: Synchronizing or translating consumer group offsets between clusters can simplify the migration process and reduce client downtime. If this is not feasible, the client migration sequence must be carefully orchestrated to meet the data processing requirements. Best Practices for Kafka Migration Regardless of whether you are migrating with or without data, the following best practices will help ensure a successful Kafka cluster migration: Do: Plan Thoroughly: Understand your current setup and define a detailed migration plan, including timelines, stakeholders, and rollback procedures. Test Extensively: Before starting the migration, test the new Kafka cluster in a staging environment that mirrors your production setup as closely as possible. Monitor in Real-Time: Use monitoring tools like Prometheus, Grafana, or Confluent Control Center to track the health and performance of both clusters during the migration. Gradual Rollout: Start with non-critical workloads to test the waters before fully migrating high-priority data streams. Don’t: Neglect Consumer Offsets: Ensure consumer offsets are correctly managed during the migration to prevent data reprocessing or loss. Ignore Data Retention Policies: Align data retention policies on both clusters to avoid unexpected data loss or storage issues. Skip Backup Plans: Always have a rollback plan and data backups in place. In case of a failure, you need to be able to revert quickly without impacting operations. Conclusion Kafka cluster migration without downtime is challenging but achievable with the right strategy and tools. Whether you’re migrating with or without data, thorough planning, testing, and execution are key to a successful transition. By following the steps and best practices outlined in this blog, you can minimize risks and ensure that your Kafka migration is smooth, efficient, and disruption-free, regardless of the Kafka provider or infrastructure you are using. --- # Building a Robust Data Pipeline with Kafka and ClickHouse URL: https://platformatory.io/blog/Building-a-Robust-Data-Pipeline-with-Kafka-and-ClickHouse/ Published: 2024-09-02 Authors: Shivaprakash Akki Categories: Kafka, Data Engineering, ClickHouse Introduction to ClickHouse Analytics with Kafka In today’s data-driven world, businesses rely heavily on real-time analytics to gain insights and make informed decisions. As data volumes grow and the need for immediate insights increases, traditional databases often struggle with challenges such as high latency, limited scalability, and the inability to handle large-scale, real-time data streams. These issues make it difficult to deliver low-latency, high-throughput analytics. This is where ClickHouse and Kafka come into play. ClickHouse is a fast, open-source columnar database management system known for its performance in real-time analytics. It’s designed to handle large volumes of data, making it ideal for scenarios where quick retrieval and processing of data are essential. Kafka, on the other hand, is a distributed streaming platform that excels at handling real-time data feeds. It’s widely used for building real-time data pipelines and streaming applications, making it a perfect match for ClickHouse when it comes to real-time analytics. Why ClickHouse and Kafka? The combination of ClickHouse and Kafka offers a powerful solution for businesses that need to process and analyze large streams of data in real time. Here’s why: Real-Time Data Ingestion: Kafka’s ability to handle real-time data streams means you can ingest data into ClickHouse as it arrives. This is crucial for applications like monitoring, IoT analytics, and real-time reporting, where insights need to be as fresh as possible. Scalability: Both ClickHouse and Kafka are designed to scale horizontally, meaning they can handle increasing loads by simply adding more nodes to the cluster. This scalability ensures that your analytics infrastructure can grow with your data. Performance: ClickHouse’s columnar storage and compression techniques allow it to query large datasets quickly, making it suitable for complex analytical queries. Kafka, along with the ClickHouse sink connector, ensures that data is efficiently streamed and delivered from Kafka topics to ClickHouse, minimizing latency in the data pipeline. Getting Started To start leveraging the power of ClickHouse and Kafka for analytics, you’ll need to set up a data pipeline where Kafka streams data into ClickHouse. Here’s a high-level overview of how this can be done: Set Up Kafka: Deploy Kafka in your environment, either on-premise or in the cloud. Create Kafka topics that will store the data produced by the applications. Configure ClickHouse: Install and configure ClickHouse on a server or cluster. Ensure that ClickHouse can handle the data volume and query load you anticipate. Connect Kafka to ClickHouse: Use Kafka Connect with the ClickHouse Kafka Connect Sink to consume data from Kafka topics and deliver it to ClickHouse tables. This setup involves configuring a Kafka Connect Sink connector with workers running the connector to efficiently read data from Kafka and write it to ClickHouse. Query and Analyze Data: Once the data is stored in ClickHouse, you can start running queries to analyze it in real-time. ClickHouse’s SQL-like query language makes it easy to perform complex analytics on the data. How ClickHouse Differs from Other Analytics Tools: Speed: ClickHouse is designed for real-time analytics and can handle billions of rows per second. It’s highly optimized for querying large datasets quickly, making it much faster than traditional databases for analytics. Columnar Storage: Unlike row-based storage used by traditional relational databases, ClickHouse uses columnar storage, which is more efficient for read-heavy analytical queries. Scalability: ClickHouse scales horizontally, allowing you to distribute data and queries across multiple servers, making it ideal for handling large-scale analytics. Query Language: ClickHouse uses SQL-like syntax but offers specialized functions and optimizations tailored for analytics, such as powerful array functions like arrayJoin() for flattening arrays into rows, and the AggregatingMergeTree engine for pre-aggregating data to optimize query performance—features that may not be available in other SQL-based systems. Real-Time Analytics: ClickHouse can handle real-time data ingestion and querying, providing immediate insights, which is crucial for monitoring and streaming analytics. These features make ClickHouse particularly well-suited for scenarios where high performance, scalability, and real-time analytics are crucial, compared to other analytics tools that might be slower or less optimized for large-scale data processing. Now Let’s configure it step by step with example Step 1: Set Up Kafka Create Kafka topics that will store the data produced by your applications. For a local setup, you can use this GitHub repository to set up Kafka and ClickHouse: cp-clickhouse. Create Kafka Topic 1 kafka-topics --create --topic kafka_topic --bootstrap-server localhost:9092 --partitions 1 --replication-factor 1 Step 2: Install the Connector Download the latest connector from the following repository: ClickHouse Kafka Connect v1.1.3. Add the downloaded connector to the plugins folder, restart the Kafka Connect service, and then list the connector plugins to check for the ClickHouse Kafka Connect plugin Step 3: Configure the Sink Connector When integrating Kafka with ClickHouse, ensure that the name of the Kafka topic (which stores the data) matches the name of the ClickHouse table (where the data will be stored). If the names don’t match, you can use a transformer, such as ExtractTopic, to modify the data or metadata so that the topic name is appropriately aligned with the table name in ClickHouse. This ensures that the data flows correctly from Kafka to the intended table in ClickHouse. Example configuration for the ClickHouse Kafka Sink Connector. For more details about each field, refer to the following documentation: ClickHouse Kafka Connect Sink Documentation. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 { "name": "voltage", "config": { "connector.class": "com.clickhouse.kafka.connect.ClickHouseSinkConnector", "tasks.max": "1", "hostname": "clickhouse", "port": "8123", "ssl": "false", "username": "default", "password": "", "database": "default", "topics": "voltage", "key.converter": "org.apache.kafka.connect.storage.StringConverter", "value.converter": "org.apache.kafka.connect.json.JsonConverter", "value.converter.schemas.enable": "false" } } Step 4: Configure the ClickHouse Table Before configuring the sink connector, ensure the table is created in ClickHouse. Otherwise, the connector will fail. Example to create a table in ClickHouse for the voltage dataset: 1 2 3 4 5 6 7 8 9 10 11 12 CREATE TABLE voltage ( Date Date, Time String, Global_active_power Float32, Global_reactive_power Float32, Voltage Float32, Global_intensity Float32, Sub_metering_1 Float32, Sub_metering_2 Float32, Sub_metering_3 Float32 ) ENGINE = MergeTree() ORDER BY (Date, Time); After creating the table, ensure that the Connect worker is running. Once confirmed, produce the data to the voltage topic. The data should match the schema of the table in ClickHouse. Example of the data to be produced to the voltage topic: 1 2 3 4 5 6 7 8 9 10 11 { "Date": "2023/08/23", "Time": "12:49:00", "Global_active_power": 3.666, "Global_reactive_power": 0.528, "Voltage": 235.68, "Global_intensity": 15.8, "Sub_metering_1": 0.0, "Sub_metering_2": 1.0, "Sub_metering_3": 17.0 } Step 5: Performing Analytics on the Table Here are a few examples of analytics you can perform on the voltage table in ClickHouse: Average Voltage Over Time: Calculates the average voltage for each date. Maximum and Minimum Global Active Power: Finds the highest and lowest values of global active power. Total Global Intensity by Date: Sums up the global intensity for each date. Voltage Distribution: Counts how frequently each voltage value occurs. Peak Hours for Energy Consumption: Identifies the time periods with the highest energy consumption. Example Use Cases Real-Time Monitoring: Companies can use ClickHouse and Kafka to monitor application performance, server metrics, or user activity in real-time, allowing for immediate action on critical events. IoT Analytics: IoT devices generate massive amounts of data that need to be processed and analyzed quickly. ClickHouse can ingest and analyze this data in real-time, providing valuable insights into device behavior and system performance. Fraud Detection: Financial institutions can stream transaction data into ClickHouse via Kafka to detect fraudulent activities as they occur, enabling them to take swift action. Conclusion ClickHouse and Kafka together form a robust foundation for real-time analytics. Whether you’re looking to monitor application performance, analyze IoT data, or detect fraud, this powerful combination can help you gain insights at the speed of data. By setting up a pipeline that streams data from Kafka to ClickHouse, you can ensure that your analytics are always up-to-date and ready to inform your business decisions. --- # Kafka Streams Push Gateway URL: https://platformatory.io/blog/streams-push-gateway/ Published: 2024-08-29 Authors: Raghavendran Nehru Categories: Kafka, Kafka Streams, API Management, Platform Engineering Introduction Organizations like DoorDash/UberEats/Swiggy/Zomato that take orders from customers and use an operational database to store the orders and keep updating the status of the orders. Status update needs to be visible for customers to make sure that they know what is happening to their orders (e.g., order accepted, order in progress, order ready for delivery, order is on route, and order is delivered, among the many possible states). What’s needed to Implement this System? To send these updates to customers (possibly hundreds or thousands per second), they need to get the updates from their suppliers (Kitchens, Restaurants), update their operational database, capture the changes (Change Data Capture or CDC) into a Kafka Topic, have consumers read the records in the Kafka Topic, sift through the ones that need to be updated, maintain connections to the customers and send the updates. In doing all this, they need to make sure that they take care of failures that occur during the updates (possibly using durable execution via Temporal Workflows and Activities). Illustrative Steps to Implementing Real-Time Order Updates Centralize Data: Store all relevant order data in a Kafka topic. Schema Management: Ensure the data in Kafka has a well-defined schema. Stream Processing: Develop a Kafka Streams application to process updates as they become available. Key Mapping: Implement a mechanism to map topics/partitions to orders/users. Stream Topology: Define a stream topology with a GroupBy key operation, repartition the topic, and make the data accessible via a web interface. Client Communication: Implement a polling or asynchronous mechanism (like WebSockets) to push updates to clients. Our Solution - Steams Push Gateway Accelerator We have built a system that takes care of automatically subscribing to updates related to specific data present in the records/messages in the Kafka Topic and routing them to the subscribers. flowchart TD %% Subgraphs for better organization subgraph KC[Kafka Cluster] T1(Kafka Topic 1) P1(Partition 1) P2(Partition 2) P3(Partition 3) end subgraph Application1 APP1[Kafka Streams Application] REST1[REST Endpoint] STORE1[RocksDB Store] APP1 -->|reads/stores data| STORE1 REST1 --> APP1 end subgraph Application2 APP2[Kafka Streams Application] REST2[REST Endpoint] STORE2[RocksDB Store] APP2 -->|reads/stores data| STORE2 REST2 --> APP2 end subgraph SA[Streams Applications] Application1 Application2 end subgraph API_Gateway API[Kong API Gateway] end subgraph Clients CLIENTS[Client] end %% Edge connections between nodes API -->|forwards requests| REST1 CLIENTS -->|request updates for specific keys| API APP1 -->|sends updates via Upgraded Websocket connection| CLIENTS API -->|forwards requests| REST2 APP2 -->|sends updates via Upgraded Websocket connection| CLIENTS %% Connection between Kafka brokers and Kafka streams applications T1 -->|partitioned data| P1 T1 -->|partitioned data| P2 T1 -->|partitioned data| P3 P1 -->|reads data| APP2 P2 -->|reads data| APP1 P3 -->|reads data| APP1 APP1 <-->|forward requests| REST2 APP2 <-->|forward requests| REST1 %% Styling classDef kafkaStyle fill:#e0f7e9,stroke:#4caf50,stroke-width:2px; class K1,K2 kafkaStyle; classDef default font-size:16px; Overview of the System Order Updates Flow Order Service: Publishes updates to a database containing customer_id and order_id. CDC Integration: A Kafka Connect application captures CDC updates and writes them to a Kafka topic. Kafka Streams Application: Consumes this data, groups it by key fields (e.g., order_id or customer_id), and stores it locally after performing a GroupBy operation. Client Communication A mobile application requests updates for a specific order via an API Gateway, which forwards the request to the Kafka Streams application. The connection is upgraded to a WebSocket, through which the Kafka Streams application sends regular updates (configurable interval) back to the client. API Gateway The API Gateway handles authentication, authorization, and request/response transformations. It provides load balancing by routing calls to different Kafka Streams Application instances, ensuring even distribution of traffic and avoiding single points of failure. API Gateway API Gateway (we recommend and use Kong that) can do the authentication. Also, provide load balancing to route the calls to a different Kafka Streams Application through an upstream (which is a Kong construct for load balancing across multiple targets with each target consisting of the hostname:port). Refer the upstreams documentation from Kong to create the upstream. Kafka Streams Application The Kafka Streams application consists of: Declarative Configuration: Specifies the Kafka bootstrap servers, application ID, state store location, input/output topics, and keys for the GroupBy operation. REST Endpoint: Configured as an upstream target for the API Gateway, enabling other Kafka Streams instances to query keys not present in their local store. Stream Topology: Manages the GroupBy operation for the specified key (e.g., order_id). WebSocket Communication: Upgrades incoming connections to WebSocket and publishes updates. Data Routing: Routes requests to the correct host if the requested key is not available locally. Declarative configuration The Kafka Streams Application can use the below declarative configuration which will be used to start the application. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 kafka: bootstrap-servers: localhost:9092 streams: application-id: kafka-streams-app default-key-serde: org.apache.kafka.common.serialization.Serdes$StringSerde default-value-serde: org.apache.kafka.common.serialization.Serdes$StringSerde properties: commit.interval.ms: 1000 cache.max.bytes.buffering: 10485760 state-dir: /tmp/kafka-streams consumer: group-id: kafka-streams-group auto-offset-reset: earliest producer: retries: 3 batch-size: 16384 buffer-memory: 33554432 topics: input-topic: orders output-topic: orders-by-key application: stream: group-by-key-enabled: true group-by-key-operation: # the key could be any field within the record and can be # addressed using a format like ‘orders.items.item_id’ key: order_id description: Group orders by their key (e.g., order ID or customer ID) update: interval:5000 description: Send updates to clients periodically using the interval (5000 means 5 seconds) REST Endpoint Retrieve the status of an order using the endpoint: /update/orders/{order_id}. Implemented using Spring Boot and integrated into the Kafka Streams Application. Web Socket Implementation The WebSocketConfig configuration class registers the handler and the path to listen to. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { private final KeyValueHandler keyValueHandler; @Autowired public WebSocketConfig(KeyValueHandler keyValueHandler) { this.keyValueHandler = keyValueHandler; } @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(keyValueHandler, "/update/orders/{key}") .addInterceptors(new KeyValueInterceptor()) .setAllowedOrigins("*"); } } We implement the logic to retrieve the data (only relevant methods are shown here) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 private void sendMessage(WebSocketSession session) throws IOException { String key = (String) session.getAttributes().get("key"); final HostStoreInfo hostStoreInfo = streamsMetadataForStoreAndKey(storeName, key); if (!thisHost(hostStoreInfo)){ session.sendMessage(new TextMessage(fetchByKey(hostStoreInfo, "update/orders/"+ key).toString())); } final ReadOnlyKeyValueStore store = kafkaStreams.store(fromNameAndType(storeName, QueryableStoreTypes.keyValueStore())); if (store == null) { throw new NotFoundException(); } // Get the value from the store final String value = store.get(key); if (value == null) { throw new NotFoundException(); } session.sendMessage(new TextMessage(new KeyValueBean(key, value).toString())); } Retrieve the data from the host that has the actual data (routing to a different host) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 private boolean thisHost(final HostStoreInfo host) { return host.getHost().equals(hostInfo.host()) && host.getPort() == hostInfo.port(); } private KeyValueBean fetchByKey(final HostStoreInfo host, final String path) { String url = String.format("http://%s:%d/%s", host, port, path); // Make the GET request ResponseEntity response = restTemplate.getForEntity(url, KeyValueBean.class); // Return the body of the response return response.getBody(); } public HostStoreInfo streamsMetadataForStoreAndKey(final String store, final String key) { return metadataService.streamsMetadataForStoreAndKey(store, key, new StringSerializer()); } Client The client could be a mobile application that makes a connection to the Kafka Streams application via the API Gateway. The connection gets upgraded to a web socket connection and the data is received at regular intervals (configured in the streams application). Once the client has received all the updates, it can close the connection. Websocket payload and response A HTTP Get connection is upgraded to a Web Socket Secure (WSS) connection. The payload structure of a WebSocket message depends on the protocol and use case. Here’s an example of a WebSocket request payload in JSON format, which is common in many real-time applications. Client to Server (Requesting Order Updates for a specific Order id) 1 2 3 4 5 6 { "type": "order_status_updates_request", "data": { "order_id": "12345" } } Server to Client (Sending Order Updates) 1 2 3 4 5 6 7 8 9 { "type": "order_status_update", "data": { "order_id": "12345", "status": "Shipped", "estimated_delivery": "2024-08-28", "tracking_number": "1Z999AA10123456784" } } Wscat commands with Basic Authentication (handled by the API Gateway) 1 2 3 4 5 echo -n "username:password" | base64 # Assume that the base64 encoding results in “dXNlcm5hbWU6cGFzc3dvcmQ=” # call the order updates api via the Kong API gateway with basic authentication wscat -c "wss://localhost:8000/update/orders" -H "Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=" After the successful connection, send 1 2 3 4 { "type": "order_updates_request", "order_id": "12345" } Conclusion The Streams Push Gateway Accelerator leverages Kafka Streams, RESTful endpoints, and WebSockets to deliver a robust, scalable solution for pushing real-time order updates to clients. By integrating with an API Gateway and employing efficient stream processing techniques, this solution ensures that customers receive timely updates on their orders, enhancing the user experience. Please contact us at hello@platformatory.com to discuss your use case and we would be happy to help! References Confluent Kafka Streams Interactive Queries: Link --- # Introduction to Temporal URL: https://platformatory.io/blog/Introduction-to-Temporal/ Published: 2024-08-21 Authors: Subramanya Madhyastha Categories: Durable Execution, Temporal, Python What is Temporal? Temporal is a durable execution platform that empowers developers to build scalable applications without compromising productivity or reliability. One of the core challenges in building distributed applications is managing complexities like handling failures, ensuring consistency, and maintaining visibility into the application state. Temporal addresses these challenges by providing powerful constructs that simplify error handling and retries, making it easier to build reliable systems. Additionally, Temporal’s tools, such as its Web UI and CLI, offer developers robust visualization and control over workflow execution. Why Use Temporal? Temporal abstracts the complexities of constructing scalable, reliable distributed systems by maintaining complete application state, enabling seamless migration of execution to another machine in the event of a host or software failure. It allows you to code resilience directly into your applications, removing the need for intricate failure and error handling logic, which accelerates development and simplifies infrastructure. Temporal eliminates the need for traditional components like queues, pub/sub systems, and schedulers, which are often used to manage complex workflows in distributed systems. Instead, Temporal inherently manages task execution, event handling, and timing, significantly reducing architectural complexity while enhancing the reliability and scalability of your applications. High-level architecture Temporal’s architecture is designed to separate the application logic from the underlying execution infrastructure, providing a clear distinction between user-hosted processes and Temporal cluster processes. To fully understand how Temporal’s architecture operates, it’s important to first grasp the key components that make up the system. These components—Workflows, Activities, Workers, and the Temporal Server—each play a distinct role in how your application logic is executed and managed. Workflows represent the heart of your application logic, defining the sequence of steps your application will take. Written using Temporal SDKs in the programming language of your choice, Workflows are designed to be deterministic, ensuring consistent outcomes given the same inputs. They are executed on your infrastructure, not directly on the Temporal Server. Activities are discrete units of business logic within your application, designed to perform specific tasks that may be prone to failure, such as interacting with external services or sending emails. Like Workflows, Activities run on your infrastructure and are managed by Temporal to ensure reliability. Workers are processes that execute your Workflows and Activities. They act as the bridge between your application logic and the Temporal Server, ensuring that your tasks are performed reliably and in the correct order. Workers constantly communicate with the Temporal Server to coordinate the execution of tasks. Temporal SDKs (Software Development Kits) are open-source collections of tools, libraries, and APIs that enable Temporal Application development. They offer a Temporal Client to interact with the Temporal Service, APIs to develop your Temporal Application, and APIs to run horizontally scalable Workers. Temporal SDKs are available in multiple languages including Go, Java, PHP, Python, TypeScript, and .NET The Temporal Server is the backbone of the Temporal system. It acts as the supervisor for your application, maintaining the source of truth for Workflow Execution Event Histories and ensuring that your distributed applications execute durably and consistently. This server can be hosted by you in a self-hosted setup or managed by Temporal through Temporal Cloud, a SaaS platform that abstracts the complexities of server management. User-hosted processes User-hosted processes in the Temporal system refer to the Worker processes that execute the Workflow and Activity code of your application. These Worker processes are hosted and operated by you, the user, and they use one of the Temporal SDKs to communicate with the Temporal Server. The Worker processes are responsible for executing the Workflow and Activity code segregated from your application and communicating with the Temporal Server, The Worker processes continuously poll the Temporal Server for Workflow and Activity tasks, and on completion of each task, they send information back to the server. The main client of the User-hosted processes is the Temporal Server. The Worker processes communicate with the Temporal Server to receive tasks and update the server on task completion. Temporal Cluster The Temporal Cluster is a group of services that together act as a component of the Temporal Platform. It includes the Temporal Server, combined with Visibility stores. One of the key components of the Temporal Server is the Frontend Service. The Frontend Service is a stateless gateway service that exposes a strongly typed API using Protocol Buffers (Protobuf). It is responsible for rate limiting, authorizing, validating, and routing all inbound calls, including those from the Worker processes. The Temporal Cluster is responsible for maintaining the state and progress of your workflows. It ensures that your distributed applications execute durably and consistently. The History Service within the Temporal Cluster manages individual Workflow Executions, handling RPCs from the User Application and the Temporal Worker, driving the Workflow Execution to completion, and storing all state required for durable execution. The Matching Service within the Temporal Cluster manages the Task Queues being polled by Temporal Worker processes, with a single task queue holding tasks for multiple Workflow Executions. The main clients of the Temporal Cluster are the User Applications and the Temporal Workers. The User Applications use one of the Temporal SDKs to communicate with the Temporal Server to start/cancel workflows, and interact with running workflows. The Temporal Workers execute the Workflow and Activity code and communicate with the Temporal Server. The User Applications and Temporal Workers communicate with the Temporal Server (part of the Temporal Cluster) using the Temporal SDKs. This communication is done via gRPC, a high-performance, open-source framework for RPC communication. The Worker processes continuously poll the Temporal Server for tasks and send updates back to the server upon task completion. Your application’s logic runs in Workers on your infrastructure, while the Temporal cluster orchestrates and manages these Workers, ensuring everything runs smoothly and reliably. With Temporal Cloud, you can offload the management of the cluster to a hosted service, while self-hosting allows you to have full control over the infrastructure. In short, Temporal is a platform designed to ensure the durable execution of your application code. Temporal handles these challenges for you, enabling your application to run reliably and consistently even in the face of unexpected issues. What does Durable execution mean? Durable Execution in the context of Temporal refers to the ability of a Workflow Execution to maintain its state and progress even in the face of failures, crashes, or server outages. This is achieved through Temporal’s use of an Event History, which records the state of a Workflow Execution at each step. If a failure occurs, the Workflow Execution can resume from the last recorded event, ensuring that progress isn’t lost. This durability is a key feature of Temporal Workflow Executions, making them reliable and resilient. It enables application code to execute effectively once and to completion, regardless of whether it takes seconds or years. In other words, Durable Execution guarantees that the main function of your application and all the steps defined in it will effectively execute just once and to completion, even in the face of failures How does Temporal achieve Durable Execution? Temporal achieves durable execution of your application code through a combination of Workflows, Activities, and an underlying Event History mechanism. Temporal automatically retries failed Activities based on the Retry Policy configured for that Activity. This allows Temporal to handle transient failures and continue the Workflow Execution once the issue is resolved. You can configure the Retry Policy to fit your needs, specifying things like the maximum number of attempts, the initial interval between retries, and the maximum interval between retries. The Event History is a key feature of Temporal that records the state of a Workflow Execution at each step. If a failure occurs, the Workflow Execution can resume from the last recorded event, ensuring that progress isn’t lost. This durability is a key feature of Temporal Workflow Executions, making them reliable and resilient. Timeouts in Temporal are used to detect application failures. They are configurable for both Workflows and Activities, allowing you to control the maximum duration of different aspects of a Workflow or Activity Execution. There are several types of timeouts that you can set: Workflow Timeouts: Each Workflow timeout controls the maximum duration of a different aspect of a Workflow Execution. Activity Timeouts: Each Activity timeout controls the maximum duration of a different aspect of an Activity Execution. Heartbeat Timeouts: A Heartbeat Timeout works in conjunction with Activity Heartbeats. An Activity Heartbeat is a ping from the Worker that is executing the Activity to the Temporal Service. If the Temporal Service does not receive a heartbeat from an Activity within the heartbeat timeout interval, it will consider the Activity as failed. Here’s an example of how Temporal handles a server crash: A Workflow is running and executing Activities. The server running the Temporal Cluster crashes. After the Temporal Server (which could be the entire Temporal Cluster if it’s a single-server setup) has stopped due to the crash, it is restarted. This could be a manual restart by an operator or an automatic restart by a system supervisor. In a multi-server setup, If one server crashes, the remaining servers in the cluster can continue to operate and maintain the state of the workflows. The Workflow is still listed and running. It picks up where it left off when the server comes back online. Because when a Temporal server crashes, the state of the workflow is preserved in its history. If a worker is unable to communicate with the server, the workflow doesn’t stop. Temporal times out the workflow task and places it back on the task queue. Another worker can then pick up the task and continue the execution by replaying the workflow history to recreate the workflow state. Developing Workflows and Activities Let us take an example and look into developing Workflows and Activities using the Temporal Python SDK. Developing a Workflow In Temporal, workflows are defined as classes. The @workflow.defn decorator is used to identify a workflow, and the @workflow.run decorator is used to mark the entry point method to be invoked. Here’s an example of a workflow definition: 1 2 3 4 5 6 7 8 9 10 @workflow.defn class GreetSomeone: @workflow.run async def run(self, name: str) -> str: greeting = await workflow.execute_activity( TranslateActivities.say_hello, name, start_to_close_timeout=timedelta(seconds=5), ) return f"{greeting}" In this example, when the run method of the GreetSomeone workflow is invoked with a name argument, it calls the say_hello activity with the same argument. Developing Activities Activities are where you execute non-deterministic code or perform operations that may fail. In the Temporal Python SDK, you define an Activity by decorating a function with @activity.defn. Here’s an example of an activity definition: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 import urllib.parse from temporalio import activity class TranslateActivities: def __init__(self, session): self.session = session @activity.defn async def say_hello(self, name: str) -> str: greeting = await self.call_service("get-spanish-greeting", name) return greeting # Utility method for making calls to the microservices async def call_service(self, stem: str, name: str) -> str: base = f"http://localhost:9999/{stem}" url = f"{base}?name={urllib.parse.quote(name)}" async with self.session.get(url) as response: response.raise_for_status() return await response.text() In this example, the say_hello activity calls the call_service method with the stem argument as “get-spanish-greeting” and the name argument. The call_service method constructs a URL using the stem and name arguments and makes a GET request to this URL using the aiohttp.ClientSession instance stored in self.session. The call_service method returns the text of the response, which is then returned by the say_hello activity. Understanding Workflow Execution in Temporal When working with Temporal, it’s essential to grasp how Workflow Execution unfolds. Let’s dive into the process, from launching Workers to handling failures and retries, to ensure you understand each step of Workflow Execution. Starting with the Worker The Workflow Execution hinges on the Worker, which runs your Workflow and Activity code. To begin, you need to launch the Worker, which involves starting a new process. In Python, this typically involves defining a main function that initializes a Temporal client, creates a Worker entity, and starts the Worker. Here’s a high-level overview of the process: Creating the Temporal Client: This client interacts with the Temporal service and manages Workflow and Activity requests. Setting Up the Worker: The Worker is created with the Temporal client, a task queue name, and the registered Workflows and Activities. Polling for Tasks: Once the Worker is running, it maintains a long-lasting connection to the Temporal Cluster, polling for new tasks. At this point, the task queue is empty, and the Worker is idle. In Python, you typically start a Worker process by defining a main function that initializes a Temporal client, creates a Worker entity, and starts the Worker. Here’s a simplified example: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 import asyncio import aiohttp from temporalio.client import Client from temporalio.worker import Worker from translate import TranslateActivities from greeting import GreetSomeone async def main(): client = await Client.connect("localhost:7233", namespace="default") # Run the worker async with aiohttp.ClientSession() as session: activities = TranslateActivities(session) worker = Worker( client, task_queue="greeting-tasks", workflows=[GreetSomeone], activities=[activities.greet_in_spanish], ) print("Starting the worker....") await worker.run() if __name__ == "__main__": asyncio.run(main()) In this example, the Worker is set up to listen to the “GREETING_TASKS” task queue and is registered with the GreetSomeone Workflow and TranslateActivities Activities. Starting the Workflow You can initiate a Workflow either using the Temporal command-line tool or programmatically through your application code. In both methods, you provide: Task Queue Name Workflow ID Workflow Type Input Data Regardless of the starting method, the Temporal Cluster records a WorkflowExecutionStarted event, marking the beginning of the Workflow Execution. Here’s an example for starting a workflow using the python sdk, let us take the workflow described in the Developing a Workflow section as the workflow to start. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 import asyncio import sys from greeting import GreetSomeone from temporalio.client import Client async def main(): # Create client connected to server at the given address client = await Client.connect("localhost:7233") # Execute a workflow handle = await client.start_workflow( GreetSomeone.run, sys.argv[1], id="greeting-workflow", task_queue="greeting-tasks", ) print(f"Started workflow. Workflow ID: {handle.id}, RunID {handle.result_run_id}") result = await handle.result() print(f"Result: {result}") if __name__ == "__main__": asyncio.run(main()) Workflow and Activity Tasks As the Workflow Execution progresses, the Temporal Cluster schedules and records various events: Workflow Task Scheduled: The Cluster schedules a new Workflow Task and logs an event. Workflow Task Started: The Worker accepts the task and starts executing the Workflow code. In the Python SDK, Activity options like start_to_close_timeout are specified as keyword arguments. The Workflow method calls execute_activity_method to invoke an Activity. The Worker must wait for the Activity to complete before proceeding. Handling Activity Execution During Activity execution: Activity Task Scheduled: The Worker notifies the Cluster that the Workflow Task is complete and requests an Activity Task. Activity Task Started: The Cluster schedules and records a new Activity Task. The Worker then runs the code for the Activity, such as calling a microservice to get a response. Failure Scenarios and Retries In the event of a Worker failure, such as a crash due to memory issues, you can recover by restarting the Worker or launching a new one. Temporal will automatically recreate the Workflow state up to the failure point, ensuring continuity. Completed Activities are not re-executed; Temporal reuses their previous results. For scenarios where the Activity encounters failures (e.g., a microservice is offline), Temporal automatically retries the Activity by default. You can configure this behavior with a Retry Policy. If the microservice is back online, the Activity will eventually succeed, and Temporal will log the appropriate events. Completing the Workflow As the Workflow code progresses and all Activities complete, the Cluster records the final WorkflowTaskCompleted event. The Workflow Execution concludes, and the client application receives the result. Use Cases Netflix uses Temporal to manage complex workflows for their content delivery and recommendation systems. Temporal helps Netflix orchestrate various microservices involved in content ingestion, metadata management, and user personalization, ensuring reliability and scalability. DoorDash employs Temporal for orchestrating its delivery and logistics operations. Temporal helps manage workflows related to order processing, delivery routing, and real-time tracking, enhancing operational efficiency and reliability. Box uses Temporal to handle file synchronization and collaborative workflows. Temporal enables Box to manage file uploads, version control, and collaborative editing, providing a scalable and fault-tolerant solution for their document management system. At Platformatory, we use Temporal for the orchestration of workflows in our Eventception platform. Eventception transforms traditional APIs to an event-driven architecture, enabling seamless integration and scalability without code changes. Temporal is used to provision necessary resources, update resources or delete resources based on user actions on the platform. These typically involves running multiple steps that need to be orchestrated for the end goal. Each user activity involving CUD (Create, Update and Delete Operations) is translated into 1 or more workflows in Temporal. The workflows are triggered as a response to a Kafka message, thus making it an event driven orchestration. Temporal allows us to manage complex, long-running processes efficiently, with automatic retries, state management, and precise execution tracking, all crucial for maintaining the robustness and reliability of our platform. To know more about Eventception, check out this video available on youtube EventCeption - Reflexive Eventing for Data-driven Application. We also use Temporal Interceptors in our Eventception platform to automatically manage workflow statuses, ensuring consistency and reducing repetitive code across our platform’s complex processes. This streamlined approach enhances operational visibility and reliability. If you wish to know more about Temporal Interceptors, make sure to check out our blog post Understanding Temporal Interceptors: Enhancing Workflow Management. Conclusion Temporal stands out as a powerful tool for managing durable executions in distributed systems. Its ability to simplify development and infrastructure while enhancing reliability makes it an invaluable asset for organizations looking to scale and innovate. Temporal also offers various amounts of courses to learn from, start your Temporal journey from the Temporal 101 course to get a hold of the basics of Temporal, the course gets you through all the basic concepts as well as how you could set up Temporal in your Local environment. --- # Unified access layer for Kafka resources: Part 2A: Python Client SDK URL: https://platformatory.io/blog/unified-access-layer-kafka-resources-part-2a/ Published: 2024-08-13 Authors: Pavan Keshavamurthy, Ashwin Venkatesan Categories: Kafka, Unified Access Layer, Platform Engineering, Infrastructure Introduction Apache Kafka is a client heavy protocol i.e. publishers/consumers get to decide the topics to connect with, authentication mechanism to use (will need to be supported by brokers) and tune their configuration for better performance. The Kafka brokers only throttle the clients and do not enforce any specific client configurations. General pattern for Kafka cluster management across many companies is centralized governance i.e. a centralized platform team manages clusters, topics, permissions, credentials etc. In these scenarios, migrating topics, credentials and clusters becomes a daunting task considering the dependency on the application teams to implement the changes in a effective manner. One way to solve this issue is to have a “Unified Access Layer for Kafka resources” which is a proxy layer between Kafka clusters and clients providing the clients insulation from the cluster specific information. Go through in detail the different approaches to constructing a Unified Access Layer for Kafka resources in the Part-1 of this blog series. Rule Based Routing Layer One of the approaches for the Unified Access Layer for Kafka resources is to have a Rule Based Routing Layer (Catalog service) which contains the metadata of the topics and their mapping with the clients. You will use a Language specific SDKs which knows how to talk to the Catalog service and fetch the required details to connect to the Kafka cluster. Typically, the client here would, before instantiating a Kafka client, locate the target Kafka service using A HTTP/REST call to the Catalog service (using some form of security: Such as basic auth or OAuth) Express an intent (such as to produce or consume) on a certain topic or domain of topics (such as prefix pattern) OR by the virtue of it’s client ID, be routed to the appropriate cluster Receive the Kafka bootstrap location Optionally, mediated credentials for both Kafka and typically, Schema registry The above, being cached with a TTL Return a Kafka client instance For more details on the implementation of the Catalog service and the Java Client SDK to talk to Catalog service, refer to the Part-2 of this blog series Python Client SDK In this blog, we will focus on the Python implementation of the custom SDK to talk to the Rule Based Routing Layer (Catalog service). Before we delve into the code, let’s understand some of the considerations for the implementation, The code changes required for transitioning to the Client SDK should be as minimal as possible Use the capabilities of a well maintained Python library for Kafka i.e. not to write new Producer and Consumer instances from scratch. We will make use of the confluent-kafka Python library as the base class for building the custom Kafka producer and consumer. Kafka Producer Wrapper We need a custom producer (platformatory_kafka.Producer) that can call the Catalog Service passing in the required information to locate the bootstrap servers and the topic. The custom producer class for the Catalog service implementation will be as below: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 import time import requests import logging from urllib.parse import urlencode, quote_plus from confluent_kafka import Producer as ConfluentProducer logging.basicConfig(level=logging.DEBUG) class Producer: def __init__(self, config): self.service_gateway_uri = config.get('service_gateway_uri') self.basic_auth = config.get('basic_auth') self.client_id = config.get('client_id') self.config_profile = config.get('config_profile') self.ttl = config.get('ttl', 300) self.additional_params = config.get('additional_params', {}) self.cache = {} self.cache_time = {} if not self.service_gateway_uri: raise ValueError("Service gateway URI must be set in the configuration") if not self.config_profile: raise ValueError("Config profile must be set in the configuration") self.producer_config = None self.producer = None def _is_cache_valid(self, key): return key in self.cache and (time.time() - self.cache_time[key]) < self.ttl def _encode_nested_params(self, params, prefix=''): """Encode nested query parameters.""" encoded_params = {} for k, v in params.items(): if isinstance(v, dict): encoded_params.update(self._encode_nested_params(v, prefix=f'{prefix}{k}.')) else: encoded_params[f'{prefix}{k}'] = v return encoded_params def _fetch_service_config(self, channel): if not self._is_cache_valid(channel): try: logging.debug(f"Fetching service config for channel: {channel}") query_params = { 'config_profile': self.config_profile, 'channel': channel } # Encode additional parameters encoded_params = self._encode_nested_params(self.additional_params) query_params.update(encoded_params) query_string = urlencode(query_params, quote_via=quote_plus) response = requests.get( f"{self.service_gateway_uri}?{query_string}", auth=self.basic_auth ) response.raise_for_status() new_config = response.json() self.cache[channel] = new_config self.cache_time[channel] = time.time() logging.debug(f"Fetched config: {self.cache[channel]}") except requests.exceptions.RequestException as e: logging.error(f"Failed to fetch service config for channel {channel}: {e}") raise else: time_left = self.ttl - (time.time() - self.cache_time[channel]) logging.debug(f"Using cached config for channel: {channel}. Time left for cache refresh: {time_left:.2f} seconds") return self.cache[channel] def _merge_config(self, config): merged_config = {} merged_config.update(config['connection']) merged_config.update(config['credentials']) merged_config.update(config['configuration']) merged_config['client.id'] = self.client_id return merged_config def _get_initial_config(self, channel): config = self._fetch_service_config(channel) initial_config = self._merge_config(config) return initial_config def produce(self, channel, value, key=None, partition=None, on_delivery=None, *args, **kwargs): if not channel: raise ValueError("Channel must be set for producing messages") if self.producer is None: self.producer_config = self._get_initial_config(channel) self.producer = ConfluentProducer(self.producer_config) service_config = self._fetch_service_config(channel) topic = service_config['channel_mapping'][channel.split('/')[-1]] logging.debug(f"Producing message to topic: {topic}") logging.debug(f"Parameters - value: {value}, key: {key}, partition: {partition}, on_delivery: {on_delivery}, args: {args}, kwargs: {kwargs}") try: if partition is None: self.producer.produce( topic=topic, value=value, key=key, callback=on_delivery, *args, **kwargs ) else: self.producer.produce( topic=topic, value=value, key=key, partition=partition, callback=on_delivery, *args, **kwargs ) except Exception as e: logging.error(f"Error in producing message: {e}") raise logging.debug(f"Message produced to topic: {topic}") def poll(self, timeout): if self.producer is not None: self.producer.poll(timeout) def flush(self): if self.producer is not None: self.producer.flush() As observed, the wrapper code calls the Catalog service to fetch the topic and configuration details on the invocation of produce method. It also initializes the Producer instance with the fetched configuration and produces the message to the dynamically fetched topic. Producer App We will create a Producer App which utilizes the above mentioned Producer wrapper to fetch the topics details and produce some messages. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 import time import random from datetime import datetime from platformatory_kafka.producer import Producer # Import the Producer wrapper # Pass in the Catalog service details and producer client-id producer_config = { 'service_gateway_uri': 'http://kong:8000/servicegw', 'basic_auth': ('user1', 'password1'), 'client_id': 'foo', 'config_profile': 'durableWrite', # Config profile from user code 'ttl': 300, # TTL set to 5 minutes (300 seconds) 'additional_params': { # Additional query parameters 'kafka': {'env': 'prod'}, 'config_profile': {'type': 'producer', 'env': 'prod'} } } # Initialize the producer producer = Producer(producer_config) def delivery_report(err, msg): """Called once for each message produced to indicate delivery result. Triggered by poll() or flush().""" if err is not None: print(f'Message delivery failed: {err}') else: print(f'Message delivered to {msg.topic()} [{msg.partition()}]') sequence_number = 0 while True: # Generate a random message with a sequence number and a human-readable timestamp current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") message = f"Message {sequence_number}: {random.randint(1, 100)} | Time: {current_time}" # Trigger any available delivery report callbacks from previous produce() calls producer.poll(0) # Asynchronously produce a message. The delivery report callback will # be triggered from the call to poll() above, or flush() below, when the # message has been successfully delivered or failed permanently. producer.produce(channel='kafka://example.com/bar', value=message.encode('utf-8'), on_delivery=delivery_report) # Wait for any outstanding messages to be delivered and delivery report # callbacks to be triggered. producer.flush() # Increment the sequence number sequence_number += 1 # Sleep for a while to simulate a slow producer time.sleep(5) # Adjust the sleep duration as needed The following details will be passed into the custom Producer to connect with Catalog service and get required configs, Service Gateway URL for the Catalog service Basic Auth details to authenticate with Catalog service Unique client ID for the producer The configProfile type for the Producer configurations The cache TTL for the configs fetched from the Catalog service When the produce method is called we send the channel value which determines the topic(s) the producer intends to publish to based on the pre-defined routing rules in the Catalog service layer. The rest of the code is similar to the general confluent-kafka Python code. Producer in Action Logs of the custom producer during execution: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 DEBUG:root:Fetching service config for channel: kafka://example.com/bar DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): kong:8000 **DEBUG:urllib3.connectionpool:http://kong:8000 "GET /servicegw?config_profile=durableWrite&channel=kafka%3A%2F%2Fexample.com%2Fbar&kafka.env=prod&config_profile.type=producer&config_profile.env=prod HTTP/11" 200 353** **DEBUG:root:Fetched config: {'channel_mapping': {'bar': 'c0t3'}, 'credentials': {'sasl.password': 'REDACTED', 'security.protocol': 'SASL_SSL', 'sasl.mechanisms': 'PLAIN', 'sasl.username': 'REDACTED'}, 'configuration': {'acks': 'all', 'retries': 3}, 'connection': {'bootstrap.servers': 'pkc-41p56.asia-south1.gcp.confluent.cloud:9092'}}** **DEBUG:root:Using cached config for channel: kafka://example.com/bar. Time left for cache refresh: 299.97 seconds** DEBUG:root:Producing message to topic: c0t3 DEBUG:root:Parameters - value: b'Message 0: 77 | Time: 2024-08-13 07:36:41', key: None, partition: None, on_delivery: , args: (), kwargs: {} DEBUG:root:Message produced to topic: c0t3 DEBUG:root:Using cached config for channel: kafka://example.com/bar. Time left for cache refresh: 294.33 seconds DEBUG:root:Producing message to topic: c0t3 DEBUG:root:Parameters - value: b'Message 1: 28 | Time: 2024-08-13 07:36:47', key: None, partition: None, on_delivery: , args: (), kwargs: {} DEBUG:root:Message produced to topic: c0t3 DEBUG:root:Using cached config for channel: kafka://example.com/bar. Time left for cache refresh: 289.24 seconds DEBUG:root:Producing message to topic: c0t3 DEBUG:root:Parameters - value: b'Message 2: 14 | Time: 2024-08-13 07:36:52', key: None, partition: None, on_delivery: , args: (), kwargs: {} DEBUG:root:Message produced to topic: c0t3 DEBUG:root:Using cached config for channel: kafka://example.com/bar. Time left for cache refresh: 284.05 seconds DEBUG:root:Producing message to topic: c0t3 DEBUG:root:Parameters - value: b'Message 3: 18 | Time: 2024-08-13 07:36:57', key: None, partition: None, on_delivery: , args: (), kwargs: {} DEBUG:root:Message produced to topic: c0t3 The custom producer talks to the Catalog service layer through REST API and fetches the configuration details. We can see the fetched config printed bold in the logs. Using the fetched confguration, the Producer is able to publish some messages to the topic c0t3. Also, the producer periodically checks if the configuration cache TTL has expired or not. Kafka Consumer Wrapper Similar to the custom producer we defined above, we will create a custom consumer (platformatory_kafka.Consumer) to talk to Catalog service layer. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 import time import requests import logging from urllib.parse import urlencode, quote_plus from confluent_kafka import Consumer as ConfluentConsumer, KafkaException, KafkaError logging.basicConfig(level=logging.DEBUG) class Consumer: def __init__(self, config): self.service_gateway_uri = config.get('service_gateway_uri') self.basic_auth = config.get('basic_auth') self.client_id = config.get('client_id') self.config_profile = config.get('config_profile') self.ttl = config.get('ttl', 300) self.additional_params = config.get('additional_params', {}) self.cache = {} self.cache_time = {} self.current_channels = [] if not self.service_gateway_uri: raise ValueError("Service gateway URI must be set in the configuration") if not self.config_profile: raise ValueError("Config profile must be set in the configuration") self.consumer_config = None self.consumer = None def _is_cache_valid(self, key): return key in self.cache and (time.time() - self.cache_time[key]) < self.ttl def _encode_nested_params(self, params, prefix=''): """Encode nested query parameters.""" encoded_params = {} for k, v in params.items(): if isinstance(v, dict): encoded_params.update(self._encode_nested_params(v, prefix=f'{prefix}{k}.')) else: encoded_params[f'{prefix}{k}'] = v return encoded_params def _fetch_service_config(self, channels): channels_key = ','.join(channels) try: logging.debug(f"Fetching service config for channels: {channels}") query_params = { 'config_profile': self.config_profile, } if len(channels) > 1: for i, channel in enumerate(channels): query_params[f'channel[{i}]'] = channel else: query_params['channel'] = channels[0] # Encode additional parameters encoded_params = self._encode_nested_params(self.additional_params) query_params.update(encoded_params) query_string = urlencode(query_params, quote_via=quote_plus) response = requests.get( f"{self.service_gateway_uri}?{query_string}", auth=self.basic_auth ) response.raise_for_status() new_config = response.json() if not self._is_cache_valid(channels_key) or new_config != self.cache.get(channels_key): self.cache[channels_key] = new_config self.cache_time[channels_key] = time.time() logging.debug(f"Fetched new config: {self.cache[channels_key]}") return True, new_config else: time_left = self.ttl - (time.time() - self.cache_time[channels_key]) logging.debug(f"Using cached config for channels: {channels}. Time left for cache refresh: {time_left:.2f} seconds") return False, self.cache[channels_key] except requests.exceptions.RequestException as e: logging.error(f"Failed to fetch service config for channels {channels}: {e}") raise def _merge_config(self, config): merged_config = {} merged_config.update(config['connection']) merged_config.update(config['credentials']) merged_config.update(config['configuration']) merged_config['client.id'] = self.client_id return merged_config def _get_initial_config(self, channels): is_new_config, config = self._fetch_service_config(channels) initial_config = self._merge_config(config) return initial_config def subscribe(self, channels, **kwargs): if not channels: raise ValueError("At least one channel must be provided for subscription") self.current_channels = channels self.consumer_config = self._get_initial_config(channels) self.consumer = ConfluentConsumer(self.consumer_config) topics = self._get_topics(channels) logging.debug(f"Subscribing to topics: {topics}") self.consumer.subscribe(topics, **kwargs) def _get_topics(self, channels): _, config = self._fetch_service_config(channels) return [config['channel_mapping'][channel.split('/')[-1]] for channel in channels] def poll(self, timeout=None): # Check for channel mapping updates self._check_for_updates() msg = self.consumer.poll(timeout=timeout) # Log time remaining for cache refresh channels_key = ','.join(self.current_channels) if channels_key in self.cache_time: time_left = self.ttl - (time.time() - self.cache_time[channels_key]) logging.debug(f"Time left for cache refresh: {time_left:.2f} seconds") if msg is None: logging.debug("No message received") return None if msg.error(): if msg.error().code() == KafkaError._PARTITION_EOF: logging.debug("End of partition reached {0}/{1}".format(msg.topic(), msg.partition())) return None else: raise KafkaException(msg.error()) logging.debug(f"Message received from topic {msg.topic()}: {msg.value().decode('utf-8')}") return msg def consume(self, num_messages=1, timeout=-1): # Check for channel mapping updates self._check_for_updates() msgs = self.consumer.consume(num_messages=num_messages, timeout=timeout) if not msgs: logging.debug("No messages received") return [] for msg in msgs: logging.debug(f"Message received from topic {msg.topic()}: {msg.value().decode('utf-8')}") return msgs def _check_for_updates(self): channels_key = ','.join(self.current_channels) is_new_config, config = self._fetch_service_config(self.current_channels) if is_new_config: logging.debug("New configuration fetched, re-subscribing with new configuration") self.subscribe(self.current_channels) def close(self): if self.consumer: self.consumer.close() On subscribe , the consumer configuration is fetched from the Catalog service and a Consumer instance is initialized. Additionally, based on the channel(s) details provides, the Consumer subscribes to the fetched topics from the Catalog service. On poll or consume , there is a check for any update to the configuration or topic details. If there is a change, the consumer is reinitialized with new configuration and/or subscribes to new topics. Additionally, it checks if the cache will need to refreshed according to the TTL provided. After which, it emulates the default behaviour of the method in the confluent-kafka library. Consumer App We will create a Consumer App which utilizes the above mentioned Consumer wrapper to fetch the topics details, subscribe to the retrieved topics and consume some messages. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 from platformatory_kafka.consumer import Consumer, KafkaException consumer_config = { 'service_gateway_uri': 'http://kong:8000/servicegw', 'basic_auth': ('user1', 'password1'), 'client_id': 'foo', 'config_profile': 'highThroughputConsumer', # Config profile from user code 'ttl': 60, # TTL set to 5 minutes (300 seconds) 'additional_params': { # Additional query parameters 'kafka': {'env': 'prod'}, 'config_profile': {'type': 'consumer', 'env': 'prod'} } } consumer = Consumer(consumer_config) # Subscribe to multiple channels channels = ['kafka://example.com/bar', 'kafka://example.com/baz'] # Initial subscription consumer.subscribe(channels) while True: try: msg = consumer.poll(1.0) if msg is None: continue if msg.error(): print(f"Consumer error: {msg.error()}") continue print(f"Received message from topic {msg.topic()}: {msg.value().decode('utf-8')}") except KeyboardInterrupt: break except Exception as e: print(f"Error: {e}") break consumer.close() The configuration which will pass to the custom consumer is similar to the custom producer we previously discussed. We will pass in the channel(s) details to the Consumer.subscribe method. This will determine the topics the Consumer will produce to based on the Routing rule defined in the Catalog service. Consumer in Action Logs of the custom consumer during execution: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 DEBUG:root:Fetching service config for channels: ['kafka://example.com/bar', 'kafka://example.com/baz'] DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): kong:8000 **DEBUG:urllib3.connectionpool:http://kong:8000 "GET /servicegw?config_profile=highThroughputConsumer&channel%5B0%5D=kafka%3A%2F%2Fexample.com%2Fbar&channel%5B1%5D=kafka%3A%2F%2Fexample.com%2Fbaz&kafka.env=prod&config_profile.type=consumer&config_profile.env=prod HTTP/11" 200 400 DEBUG:root:Fetched new config: {'channel_mapping': {'bar': 'c0t3', 'baz': 'c0t2'}, 'credentials': {'sasl.password': 'REDACTED', 'security.protocol': 'SASL_SSL', 'sasl.mechanisms': 'PLAIN', 'sasl.username': 'REDACTED'}, 'configuration': {'group.id': 'yourstupidpythongroup', 'fetch.min.bytes': 50000}, 'connection': {'bootstrap.servers': 'pkc-41p56.asia-south1.gcp.confluent.cloud:9092'}} DEBUG:root:Fetching service config for channels: ['kafka://example.com/bar', 'kafka://example.com/baz']** DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): kong:8000 DEBUG:urllib3.connectionpool:http://kong:8000 "GET /servicegw?config_profile=highThroughputConsumer&channel%5B0%5D=kafka%3A%2F%2Fexample.com%2Fbar&channel%5B1%5D=kafka%3A%2F%2Fexample.com%2Fbaz&kafka.env=prod&config_profile.type=consumer&config_profile.env=prod HTTP/11" 200 400 DEBUG:root:Using cached config for channels: ['kafka://example.com/bar', 'kafka://example.com/baz']. Time left for cache refresh: 59.95 seconds **DEBUG:root:Subscribing to topics: ['c0t3', 'c0t2']** DEBUG:root:Fetching service config for channels: ['kafka://example.com/bar', 'kafka://example.com/baz'] DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): kong:8000 DEBUG:urllib3.connectionpool:http://kong:8000 "GET /servicegw?config_profile=highThroughputConsumer&channel%5B0%5D=kafka%3A%2F%2Fexample.com%2Fbar&channel%5B1%5D=kafka%3A%2F%2Fexample.com%2Fbaz&kafka.env=prod&config_profile.type=consumer&config_profile.env=prod HTTP/11" 200 400 DEBUG:root:Using cached config for channels: ['kafka://example.com/bar', 'kafka://example.com/baz']. Time left for cache refresh: 59.95 seconds **DEBUG:root:Time left for cache refresh: 58.95 seconds** DEBUG:root:No message received DEBUG:root:Fetching service config for channels: ['kafka://example.com/bar', 'kafka://example.com/baz'] DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): kong:8000 DEBUG:urllib3.connectionpool:http://kong:8000 "GET /servicegw?config_profile=highThroughputConsumer&channel%5B0%5D=kafka%3A%2F%2Fexample.com%2Fbar&channel%5B1%5D=kafka%3A%2F%2Fexample.com%2Fbaz&kafka.env=prod&config_profile.type=consumer&config_profile.env=prod HTTP/11" 200 400 DEBUG:root:Using cached config for channels: ['kafka://example.com/bar', 'kafka://example.com/baz']. Time left for cache refresh: 58.93 seconds DEBUG:root:Time left for cache refresh: 57.93 seconds DEBUG:root:No message received DEBUG:root:Fetching service config for channels: ['kafka://example.com/bar', 'kafka://example.com/baz'] DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): kong:8000 DEBUG:urllib3.connectionpool:http://kong:8000 "GET /servicegw?config_profile=highThroughputConsumer&channel%5B0%5D=kafka%3A%2F%2Fexample.com%2Fbar&channel%5B1%5D=kafka%3A%2F%2Fexample.com%2Fbaz&kafka.env=prod&config_profile.type=consumer&config_profile.env=prod HTTP/11" 200 400 DEBUG:root:Using cached config for channels: ['kafka://example.com/bar', 'kafka://example.com/baz']. Time left for cache refresh: 57.92 seconds DEBUG:root:Time left for cache refresh: 56.92 seconds DEBUG:root:No message received DEBUG:root:Fetching service config for channels: ['kafka://example.com/bar', 'kafka://example.com/baz'] DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): kong:8000 DEBUG:urllib3.connectionpool:http://kong:8000 "GET /servicegw?config_profile=highThroughputConsumer&channel%5B0%5D=kafka%3A%2F%2Fexample.com%2Fbar&channel%5B1%5D=kafka%3A%2F%2Fexample.com%2Fbaz&kafka.env=prod&config_profile.type=consumer&config_profile.env=prod HTTP/11" 200 400 DEBUG:root:Using cached config for channels: ['kafka://example.com/bar', 'kafka://example.com/baz']. Time left for cache refresh: 56.90 seconds DEBUG:root:Time left for cache refresh: 55.90 seconds DEBUG:root:No message received DEBUG:root:Fetching service config for channels: ['kafka://example.com/bar', 'kafka://example.com/baz'] DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): kong:8000 DEBUG:urllib3.connectionpool:http://kong:8000 "GET /servicegw?config_profile=highThroughputConsumer&channel%5B0%5D=kafka%3A%2F%2Fexample.com%2Fbar&channel%5B1%5D=kafka%3A%2F%2Fexample.com%2Fbaz&kafka.env=prod&config_profile.type=consumer&config_profile.env=prod HTTP/11" 200 400 DEBUG:root:Using cached config for channels: ['kafka://example.com/bar', 'kafka://example.com/baz']. Time left for cache refresh: 55.89 seconds DEBUG:root:Time left for cache refresh: 54.89 seconds DEBUG:root:No message received DEBUG:root:Fetching service config for channels: ['kafka://example.com/bar', 'kafka://example.com/baz'] DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): kong:8000 DEBUG:urllib3.connectionpool:http://kong:8000 "GET /servicegw?config_profile=highThroughputConsumer&channel%5B0%5D=kafka%3A%2F%2Fexample.com%2Fbar&channel%5B1%5D=kafka%3A%2F%2Fexample.com%2Fbaz&kafka.env=prod&config_profile.type=consumer&config_profile.env=prod HTTP/11" 200 400 DEBUG:root:Using cached config for channels: ['kafka://example.com/bar', 'kafka://example.com/baz']. Time left for cache refresh: 54.87 seconds DEBUG:root:Time left for cache refresh: 53.87 seconds DEBUG:root:No message received DEBUG:root:Fetching service config for channels: ['kafka://example.com/bar', 'kafka://example.com/baz'] DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): kong:8000 DEBUG:urllib3.connectionpool:http://kong:8000 "GET /servicegw?config_profile=highThroughputConsumer&channel%5B0%5D=kafka%3A%2F%2Fexample.com%2Fbar&channel%5B1%5D=kafka%3A%2F%2Fexample.com%2Fbaz&kafka.env=prod&config_profile.type=consumer&config_profile.env=prod HTTP/11" 200 400 DEBUG:root:Using cached config for channels: ['kafka://example.com/bar', 'kafka://example.com/baz']. Time left for cache refresh: 53.86 seconds DEBUG:root:Time left for cache refresh: 52.86 seconds DEBUG:root:No message received DEBUG:root:Fetching service config for channels: ['kafka://example.com/bar', 'kafka://example.com/baz'] DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): kong:8000 DEBUG:urllib3.connectionpool:http://kong:8000 "GET /servicegw?config_profile=highThroughputConsumer&channel%5B0%5D=kafka%3A%2F%2Fexample.com%2Fbar&channel%5B1%5D=kafka%3A%2F%2Fexample.com%2Fbaz&kafka.env=prod&config_profile.type=consumer&config_profile.env=prod HTTP/11" 200 400 DEBUG:root:Using cached config for channels: ['kafka://example.com/bar', 'kafka://example.com/baz']. Time left for cache refresh: 52.85 seconds DEBUG:root:Time left for cache refresh: 51.85 seconds DEBUG:root:No message received DEBUG:root:Fetching service config for channels: ['kafka://example.com/bar', 'kafka://example.com/baz'] DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): kong:8000 DEBUG:urllib3.connectionpool:http://kong:8000 "GET /servicegw?config_profile=highThroughputConsumer&channel%5B0%5D=kafka%3A%2F%2Fexample.com%2Fbar&channel%5B1%5D=kafka%3A%2F%2Fexample.com%2Fbaz&kafka.env=prod&config_profile.type=consumer&config_profile.env=prod HTTP/11" 200 400 DEBUG:root:Using cached config for channels: ['kafka://example.com/bar', 'kafka://example.com/baz']. Time left for cache refresh: 51.84 seconds DEBUG:root:Time left for cache refresh: 50.84 seconds DEBUG:root:No message received DEBUG:root:Fetching service config for channels: ['kafka://example.com/bar', 'kafka://example.com/baz'] DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): kong:8000 DEBUG:urllib3.connectionpool:http://kong:8000 "GET /servicegw?config_profile=highThroughputConsumer&channel%5B0%5D=kafka%3A%2F%2Fexample.com%2Fbar&channel%5B1%5D=kafka%3A%2F%2Fexample.com%2Fbaz&kafka.env=prod&config_profile.type=consumer&config_profile.env=prod HTTP/11" 200 400 DEBUG:root:Using cached config for channels: ['kafka://example.com/bar', 'kafka://example.com/baz']. Time left for cache refresh: 50.82 seconds DEBUG:root:Time left for cache refresh: 49.82 seconds DEBUG:root:No message received DEBUG:root:Fetching service config for channels: ['kafka://example.com/bar', 'kafka://example.com/baz'] DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): kong:8000 DEBUG:urllib3.connectionpool:http://kong:8000 "GET /servicegw?config_profile=highThroughputConsumer&channel%5B0%5D=kafka%3A%2F%2Fexample.com%2Fbar&channel%5B1%5D=kafka%3A%2F%2Fexample.com%2Fbaz&kafka.env=prod&config_profile.type=consumer&config_profile.env=prod HTTP/11" 200 400 DEBUG:root:Using cached config for channels: ['kafka://example.com/bar', 'kafka://example.com/baz']. Time left for cache refresh: 49.81 seconds DEBUG:root:Time left for cache refresh: 48.81 seconds DEBUG:root:No message received DEBUG:root:Fetching service config for channels: ['kafka://example.com/bar', 'kafka://example.com/baz'] DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): kong:8000 DEBUG:urllib3.connectionpool:http://kong:8000 "GET /servicegw?config_profile=highThroughputConsumer&channel%5B0%5D=kafka%3A%2F%2Fexample.com%2Fbar&channel%5B1%5D=kafka%3A%2F%2Fexample.com%2Fbaz&kafka.env=prod&config_profile.type=consumer&config_profile.env=prod HTTP/11" 200 400 DEBUG:root:Using cached config for channels: ['kafka://example.com/bar', 'kafka://example.com/baz']. Time left for cache refresh: 48.79 seconds DEBUG:root:Time left for cache refresh: 47.79 seconds DEBUG:root:No message received DEBUG:root:Fetching service config for channels: ['kafka://example.com/bar', 'kafka://example.com/baz'] DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): kong:8000 DEBUG:urllib3.connectionpool:http://kong:8000 "GET /servicegw?config_profile=highThroughputConsumer&channel%5B0%5D=kafka%3A%2F%2Fexample.com%2Fbar&channel%5B1%5D=kafka%3A%2F%2Fexample.com%2Fbaz&kafka.env=prod&config_profile.type=consumer&config_profile.env=prod HTTP/11" 200 400 DEBUG:root:Using cached config for channels: ['kafka://example.com/bar', 'kafka://example.com/baz']. Time left for cache refresh: 47.78 seconds DEBUG:root:Time left for cache refresh: 47.19 seconds **DEBUG:root:Message received from topic c0t3: Message 23: 34 | Time: 2024-08-13 07:38:39** DEBUG:root:Fetching service config for channels: ['kafka://example.com/bar', 'kafka://example.com/baz'] DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): kong:8000 DEBUG:urllib3.connectionpool:http://kong:8000 "GET /servicegw?config_profile=highThroughputConsumer&channel%5B0%5D=kafka%3A%2F%2Fexample.com%2Fbar&channel%5B1%5D=kafka%3A%2F%2Fexample.com%2Fbaz&kafka.env=prod&config_profile.type=consumer&config_profile.env=prod HTTP/11" 200 400 DEBUG:root:Using cached config for channels: ['kafka://example.com/bar', 'kafka://example.com/baz']. Time left for cache refresh: 47.18 seconds DEBUG:root:Time left for cache refresh: 46.18 seconds DEBUG:root:No message received Similar to the custom producer, the custom consumer talks to the Catalog service through REST API and fetches the configurations for the Consumer client and the required topics based on the channel provided. It then subscribes to the fetched topics and starts consuming messages. It also periodically checks the cache TTL for the configuration refresh. Conclusion In this blog post, we covered the Python implementation for the custom client SDK to talk to the Rule Based Routing Layer to dynamically fetch the topic details and client configuration. We talked through the considerations and the nuances in the implementation. As next steps, we will package this implementation as a Python library to enable users to implement it with ease. --- # Understanding Temporal Interceptors: Enhancing Workflow Management URL: https://platformatory.io/blog/Understanding-Temporal-Interceptors/ Published: 2024-08-13 Authors: Subramanya Madhyastha Categories: Durable Execution, Temporal Introduction Temporal is an open-source platform designed for managing workflows and microservices orchestration, providing features like state persistence, task queuing, and scheduling. One of its powerful features is the ability to use interceptors, which enable you to customize and extend the behavior of workflows, activities, and other components. This blog primarily focuses on interceptors in the Temporal Python SDK, while exploring what they are, how they function, and how you can leverage them to enhance your workflow management. So What are Temporal Interceptors? Interceptors in Temporal are hooks that allow developers to insert custom logic at various points in the execution of workflows and activities. They can be used to implement cross-cutting concerns such as logging, metrics collection, error handling, retries, and security checks without polluting the core business logic. Types of Interceptors Temporal provides SDKs for various programming languages, and Interceptors can differ between different Temporal SDKs. For example, the Java SDK and Python SDK have different sets of interceptors and the way they are implemented and used can vary. While each Temporal SDK has its own set of interceptors, the way they are implemented and used can vary. The types of interceptors are not inherently different across SDKs, but their implementation and usage can differ based on the language and the SDK’s design. For example, in the Java SDK, interceptors are located in the io.temporal.common.interceptors package and include types such as WorkflowOutboundCallsInterceptor, WorkflowInboundCallsInterceptor, ActivityInboundCallsInterceptor, ScheduleClientCallsInterceptor, WorkerInterceptor, WorkflowClientCallsInterceptor, and WorkflowClientInterceptor. In the Python SDK, the interceptors are part of the temporalio package. The Python SDK includes types such as temporalio.worker._interceptor, temporalio.contrib.opentelemetry.TracingInterceptor, temporalio.contrib.opentelemetry.TracingWorkflowInboundInterceptor, and temporalio.client.OutboundInterceptor. So, while both SDKs use interceptors to intercept calls within the Temporal system, the specific types and their implementations can vary between the two SDKs. This is largely due to the differences in language features and idioms, as well as the design of the SDKs themselves. If we were to take the Python SDK as an example, there are primarily 2 types of Interceptors. Interceptor: This is the base class for creating custom interceptors. It provides methods that can be overridden to intercept activities and workflows. The primary methods in this class are intercept_activity and workflow_interceptor_class. WorkflowInboundInterceptor: The WorkflowInboundInterceptor class is used to intercept inbound calls to a workflow. It provides several methods that can be overridden to intercept different types of calls like init , execute_workflow, handle_signal, handle_query. While these are only the primary Interceptor classes, there are specific implementations of these classes that extend from them. contrib.opentelemetry.TracingInterceptor: This is a specific implementation of the Interceptor class. It extends Interceptor and overrides its methods to add OpenTelemetry tracing functionality. This interceptor is used for tracing purposes. This is an OpenTelemetry tracing interceptor. It provides methods like init, intercept_activity, intercept_client, and workflow_interceptor_class. It automatically creates and propagates OpenTelemetry spans for all client calls, activities, and workflow invocations on the worker. contrib.opentelemetry.TracingWorkflowInboundInterceptor: This is another type of interceptor used for tracing. This is a specific implementation of the WorkflowInboundInterceptor class. It extends WorkflowInboundInterceptor and overrides its methods to add OpenTelemetry tracing functionality. It provides methods like handle_query, handle_signal, handle_update_handler, and handle_update_validator. This interceptor can be used when you want to add tracing to inbound workflow calls. Each of these interceptors can be used in different scenarios depending on your specific use case and requirements. For example, if you want to add tracing to your application, you might use the TracingInterceptor and TracingWorkflowInboundInterceptor. If you want to add custom logic to the execution of an activity, you might use the worker.Interceptor. If you want to add custom logic to outbound calls made from within workflows, you might use the client.OutboundInterceptor. How Interceptors Work Interceptors are run in a chain, and all interceptors work similarly. They accept two arguments: input and next, where next calls the next interceptor in the chain. All interceptor methods are optional—it’s up to the implementer to choose which methods to intercept. For example let us take the The WorkflowInboundInterceptor class in Temporal Python SDK, it is used to intercept inbound calls to a workflow. It provides several methods that can be overridden to intercept different types of calls. Below are the main methods provided by the WorkflowInboundInterceptor class for intercepting inbound calls to the workflow. You can find more details about the WorkflowInboundInterceptor class and its methods in the Temporal Python SDK documentation. __init__: This method is used to initialize a WorkflowInboundInterceptor instance. The next parameter is the next interceptor in the chain. The default implementation of all calls is to delegate to the next interceptor. execute_workflow: This method is called to run the workflow. It takes an ExecuteWorkflowInput object as an argument and returns any value. The default implementation is to call execute_workflow on the next interceptor in the chain. handle_signal: This method is called to handle a signal. It takes a HandleSignalInput object as an argument. The default implementation is to call handle_signal on the next interceptor in the chain. handle_query: This method is called to handle a query. It takes a HandleQueryInput object as an argument and returns any value. The default implementation is to call handle_query on the next interceptor in the chain. To get an idea of how an Interceptor will work let us look into the execute_workflow method of the WorkflowInboundInterceptor class: The execute_workflow method is called when a workflow is about to be executed. It takes an ExecuteWorkflowInput object as an argument, which contains the information needed to execute the workflow, such as the workflow type and arguments. The method returns the result of the workflow execution. Let’s consider a simple custom logic where we print a message before and after the execution of the workflow. Here’s how you might implement this in a WorkflowInboundInterceptor: 1 2 3 4 5 6 7 8 9 10 class MyWorkflowInboundInterceptor(WorkflowInboundInterceptor): async def execute_workflow(self, input: ExecuteWorkflowInput) -> Any: print("About to execute workflow") try: result = await self.next.execute_workflow(input) print("Workflow executed successfully") except Exception as e: print("Workflow execution failed") raise e return result Here’s a more detailed explanation of the execution, In this code: We define a new class MyWorkflowInboundInterceptor that extends the WorkflowInboundInterceptor class. This means that MyWorkflowInboundInterceptor is a type of WorkflowInboundInterceptor and can override its methods to add custom logic. We override the execute_workflow method. This method is called when a workflow is about to be executed. The input parameter is an ExecuteWorkflowInput object that contains the information needed to execute the workflow. At the start of the execute_workflow method, we add some custom pre-execution logic. In this case, we print the message “About to execute workflow”. This message will be printed every time a workflow is about to be executed. We then call the execute_workflow method on the next interceptor in the chain. This is done using the await keyword because execute_workflow is an asynchronous method that returns a future. The await keyword pauses the execution of the current method until the future is resolved. If the call to execute_workflow on the next interceptor is successful, it means that the workflow was executed successfully. In this case, we add some custom post-execution logic to print the message “Workflow executed successfully”. If the call to execute_workflow on the next interceptor throws an exception, it means that the workflow execution failed. In this case, we catch the exception, print the message “Workflow execution failed”, and then re-raise the exception. This allows the exception to be propagated up the call stack. Finally, the execute_workflow method returns the result of the workflow execution. This result is then passed back up the chain of interceptors, allowing each interceptor to potentially modify or act upon the result before it’s ultimately returned to the caller. To give you a visual representation, here’s a flowchart of how this works: Implementing Interceptors in Your Temporal Application To implement interceptors in your Temporal application using the Python SDK, you would typically follow these steps: Create an instance of the interceptor: First, create your interceptor class that implements the relevant Temporal interceptor interface. This could be a Workflow or Activity interceptor depending on your needs. Let us look at an example: The below provided code defines two classes: Workflow_Interceptor and Test_Interceptor. Workflow_Interceptor is a subclass of WorkflowInboundInterceptor and overrides the execute_workflow method. This method is called when a workflow is about to be executed. The input parameter is an ExecuteWorkflowInput object that contains the information needed to execute the workflow. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 class Workflow_Interceptor(WorkflowInboundInterceptor): async def execute_workflow(self, input: ExecuteWorkflowInput) -> Any: try: result = await super().execute_workflow(input) print("Workflow successfully executed.") return result except Exception as e: print("Workflow execution failed.") capture_exception() raise e class Test_Interceptor(Interceptor): def workflow_interceptor_class( self, input: WorkflowInterceptorClassInput ) -> Optional[Type[WorkflowInboundInterceptor]]: return Workflow_Interceptor When a workflow is about to be executed, Temporal calls the workflow_interceptor_class method of TestInterceptor to get the class of the workflow interceptor to use. workflow_interceptor_class returns Workflow_Interceptor, so Temporal creates an instance of Workflow_Interceptor and calls its execute_workflow method to execute the workflow. execute_workflow tries to execute the workflow by calling the execute_workflow method of WorkflowInboundInterceptor. If the workflow execution is successful, it prints “Workflow successfully executed.” and returns the result. If an exception occurs, it prints “Workflow execution failed.”, captures the exception, and re-raises the exception. Register the interceptor: In Temporal’s Python SDK, you can register an interceptor within the worker definition. This is done when creating a Worker instance, where you can pass your interceptor as part of the interceptors parameter. The below code is an example of a worker which is created with an interceptor that is defined in the above code snippet. Here’s the example: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 # Connect to Temporal server client = await Client.connect("hostname:port", namespace="default") # Create an instance of TranslateActivities without session activities = TranslateActivities() # Create a worker with an interceptor worker = Worker( client, task_queue="greeting-tasks", workflows=[GreetSomeone], activities=[activities.greet_in_spanish], interceptors=[Test_Interceptor()], ) Use the interceptor: Once the interceptor is set, it will automatically intercept all relevant calls for every workflow associated with the worker. When the interceptor is defined in a worker definition, it will apply to all workflows managed by that worker. The following code defines an activity, which triggers the intended logic in the Interceptor upon its completion (i.e. completion of the workflow) in this case a print statement in the Interceptor stating “Workflow successfully executed.” 1 2 3 4 5 6 7 8 9 10 11 class TranslateActivities: def __init__(self): pass @activity.defn async def greet_in_spanish(self, name: str) -> str: greeting = self.generate_greeting(name) return greeting # Method to generate greeting message def generate_greeting(self, name: str) -> str: return f"Hola, {name}!" Similarly to implement interceptors in your Temporal application using the Java SDK, you would typically follow these steps: Create an instance of the interceptor: First, create your interceptor class that implements the relevant Temporal interceptor interface. This could be a WorkflowInboundCallsInterceptor or WorkflowOutboundCallsInterceptor depending on your needs. Let’s look at an example: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 public class MyWorkflowInterceptor implements WorkflowInboundCallsInterceptor { private final WorkflowInboundCallsInterceptor next; public MyWorkflowInterceptor(WorkflowInboundCallsInterceptor next) { this.next = next; } @Override public WorkflowOutput execute(WorkflowInput input) { try { System.out.println("Workflow is about to be executed."); WorkflowOutput output = next.execute(input); System.out.println("Workflow executed successfully."); return output; } catch (Exception e) { System.out.println("Workflow execution failed."); throw e; } } } In this example, MyWorkflowInterceptor is a class that implements the WorkflowInboundCallsInterceptor interface. It overrides the execute method to add custom logic before and after the workflow execution. Register the interceptor: The interceptor can be registered when creating the WorkerFactory: 1 2 3 4 WorkerFactoryOptions factoryOptions = WorkerFactoryOptions.newBuilder() .setWorkflowInterceptor(new MyWorkflowInterceptor()) .build(); WorkerFactory factory = WorkerFactory.newInstance(client, factoryOptions); In this code, MyWorkflowInterceptor is registered as the workflow interceptor when creating the WorkerFactory. Use the interceptor: Once the interceptor is registered, it will automatically intercept all relevant calls for every workflow associated with the worker, just like when used in the Python SDK. You can find more details about the WorkflowInboundCallsInterceptor and WorkflowOutboundCallsInterceptor interfaces in the Temporal Java SDK documentation. Benefits of Using Interceptors Interceptors in Temporal provide a powerful mechanism for adding custom logic around the execution of workflows and activities, or modifying the behavior of certain functions. Here are some benefits of using interceptors: Tracing and Logging: Interceptors can be used to add tracing and logging to your application. This can help you monitor the execution of your workflows and activities, and diagnose issues. For example, the TracingInterceptor in the Python SDK automatically creates and propagates OpenTelemetry spans for all client calls, activities, and workflow invocations on the worker. Modifying Behavior: Interceptors can modify the behavior of workflows and activities. For example, they can change the options for workflow/activity execution to apply company policies. Auditing: Interceptors can be used to add auditing to your application. This can help you keep track of changes and actions in your application. Error Handling: Interceptors can be used to add custom error handling to your application. This can help you manage and recover from errors in a consistent way. By encapsulating cross-cutting concerns in interceptors, you keep the core business logic clean and maintainable. This makes it easier to reuse and compose different interceptors across multiple workflows and activities. Use Cases At Platformatory, we have leveraged Temporal interceptors to streamline the workflow status management in one of our products. In our system, workflows represent complex processes with multiple steps, and keeping track of their completion status, whether successful or failed, is crucial for maintaining operational visibility and observability.Temporal also provides several tools to view and manage the status of workflows like Temporal Web UI which Provides detailed information about workflow execution, including input values, timeout configurations, retries, errors, and more and Temporal CLI which Allows you to describe the workflow and get information about its status. Actions to take when a workflow fails can be implemented in your interceptor’s logic or in a separate component that monitors the workflow statuses. These actions could retry the workflow, or fall back to a backup workflow. Although you might manually update the status of a workflow at the start or end of its execution by embedding this logic within the workflow’s code, this approach can lead to repetitive and error-prone code, where each workflow must handle its own status updates. To address this, we’ve implemented interceptors to automatically manage workflow statuses, reducing the need for repetitive code and ensuring consistency across our platform. Conclusion Temporal interceptors are a powerful feature that allows you to enhance and customize the behavior of your workflows and activities. They not only improve the observability and robustness of your applications but also keeps your core business logic clean and maintainable. Whether you’re looking to add custom logging, implement company policies, or handle errors in a consistent manner, Temporal interceptors offer a powerful solution. --- # Monitoring: How to monitor AWS MSK Cluster URL: https://platformatory.io/blog/Monitoring-How-to-monitor-AWS-MSK-Kafka-Cluster/ Published: 2024-08-13 Authors: Zeenia Gupta Categories: Kafka, Observability, AWS MSK Monitoring: How to monitor AWS MSK Kafka Cluster Introduction Amazon Managed Streaming for Apache Kafka (MSK) securely streams data with a fully managed, highly available Apache Kafka service, utilizing an open-source version of Apache Kafka which allows you to focus on building and running applications. A properly running Kafka cluster can handle a significant amount of data. So, it is essential to monitor the health of your Kafka cluster to maintain reliability and performance of your Kafka cluster. In this blog, we’ll explore how to monitor the MSK Kafka cluster using open-source tools like Prometheus and Grafana. With the help of these tools, we can get a good understanding of our Kafka cluster’s health, identify issues, and make better decisions about resource allocation and budgeting. To keep your Kafka cluster running optimally, it is important to focus on these three things: optimizing performance, high availability, and managing costs. By monitoring load utilization, we can identify which broker is struggling due to high load, while tracking resource usage which helps optimize performance. Additionally, tracking the cost associated with specific resources, allows you for better budget planning and prioritization according to your business needs. Why Do We Choose Open-Source Monitoring Over CloudWatch? We’re using open-source monitoring tools like Prometheus and Grafana instead of AWS CloudWatch because CloudWatch charges additional costs for monitoring various resources when you create a cluster. With basic monitoring in CloudWatch, you only get metrics related to broker and cluster. However, by using the open-source monitoring tools, you can monitor all the resources such as topics, partitions, brokers, and clients without any additional cost. This approach not only saves money but also time, as it provides detailed cost metrics per resource. In contrast, AWS Cost Explorer groups all expenses like outbound charges, data transfer within a region, and storage provisioning under the Amazon MSK category, making it a little difficult to find which resource is costing you the most. With Open-source monitoring, you can identify which resource is costing you the most and prioritize your budget and resource allocation accordingly. Process Flow for Monitoring Apache Kafka with Amazon MSK Here, we created a VPC with three subnets. The number of subnets should match the number of brokers in your cluster. We also created a security group that is attached to both the MSK Kafka cluster and the EC2 instance, so ensure that the security group is the same for both. Since we are using SASL/SCRAM authentication, you need to associate a secret with the cluster, which we will create in the Secrets Manager. Refer to the following document for instructions on creating a secret in the Secrets Manager. Note: Ensure that you enable open monitoring with Prometheus, for both the JMX and Node Exporter, when creating the MSK Kafka cluster. Configure the following inbound rules for the security groups associated with the cluster: SSH Port: 22 Prometheus Port: 9090 Grafana Port: 3000 These inbound rules will allow access to the Prometheus and Grafana dashboards via your browser. We will use open-source Apache Kafka metrics instead of CloudWatch. Prometheus will collect data from the EC2 instance, and Grafana will retrieve the data from Prometheus. Configuration Prometheus Configuration 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 global: scrape\_interval: 15s evaluation\_interval: 15s scrape\_configs: - job\_name: 'Kafka-broker' file\_sd\_configs: - files: - 'targets.json' static\_configs: - labels: env: "dev" relabel\_configs: - source\_labels: [\_\_address\_\_] target\_label: instance regex: '([^:]+)(:[0-9]+)?' replacement: '${1}' As we are monitoring MSK cluster for both Kafka broker as well as node, instead of writing all the broker DNS names here, we have created a “target.json” file in which we have included the broker DNS names and the port. Amazon MSK uses port 11001 for the JMX Exporter and port 11002 for the Node Exporter. targets.json 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 [ { labels": { "job": "Kafka-broker", "env": "dev", "cluster": "monitoring-msk" }, "targets": [ "b-1.monitoringmsk.a2801f.c18.Kafka.us-east-1.amazonaws.com:11001", "b-2.monitoringmsk.a2801f.c18.Kafka.us-east-1.amazonaws.com:11001", "b-3.monitoringmsk.a2801f.c18.Kafka.us-east-1.amazonaws.com:11001" ] }, { "labels": { "job": "node", "env": "dev", "cluster": "monitoring-msk" }, "targets": [ "b-1.monitoringmsk.a2801f.c18.Kafka.us-east-1.amazonaws.com:11002", "b-2.monitoringmsk.a2801f.c18.Kafka.us-east-1.amazonaws.com:11002", "b-3.monitoringmsk.a2801f.c18.Kafka.us-east-1.amazonaws.com:11002" ] } ] Grafana Dashboards Kafka Cluster Utilization In this We are monitoring the Utilization of our MSK cluster such as: Thread Utilization The network and request handler capacity metric group contains metrics regarding the amount of time the request handler and network process are used. Kafka networks processor threads are responsible for reading and writing the data to Kafka clients across the network. Meanwhile, the request handler threads are responsible for client requests i.e. reading and writing messages to the disk. The metrics available are: Request Handler |Expr: 100 - Kafka_server_KafkaRequestHandlerPool_Count{name=”RequestHandlerAvgIdlePercent”, job=”Kafka-broker”, env=~”$env”, instance=~”$instance”} Network Processor Expr: 100 - Kafka_network_SocketServer_Value{name="NetworkProcessorAvgIdlePercent", job="Kafka-broker", env=~"$env", instance=~"$instance"} The Percentage of Request handler and Network processor usage is in between 0-100. If it’s 0 then all resources are used and 100 i.e. all resources are available. System Utilization Here, we are monitoring the cluster or broker load, which allows us to identify which brokers are overloaded. The broker can be overloaded when partitions in the topic are given correctly. In that case, increasing the number of partitions could help the load across the Kafka brokers. Similarly, there are other scenarios where adjustments can optimize performance. This not only reduces the pressure on the request handler , but also Kafka throughput will increase The metrics available are: . Disk I/O utilization: Expr: (rate(node_disk_read_bytes_total{job="node"}[5m]) + rate(node_disk_written_bytes_total{job="node"}[5m]))/1000000000 |Percentage: $Expr * 100 Memory Usage Expr: (sum(java_lang_Memory_HeapMemoryUsage_used{job="Kafka-broker", instance=~"$instance", env="dev"}) + sum(java_lang_Memory_NonHeapMemoryUsage_used{job="Kafka-broker", instance=~"$instance", env="dev"})) + (sum(java_lang_Memory_HeapMemoryUsage_committed{job="Kafka-broker", instance=~"$instance", env="dev"}) + sum(java_lang_Memory_NonHeapMemoryUsage_committed{job="Kafka-broker", instance=~"$instance", env="dev"}) |Percentage: $Expr * 100* CPU Usage Expr: irate(process_cpu_seconds_total{job="node", env=~"$env", instance=~"$instance"}[5m])*100 Resource Usage Based In this mode, we are calculating the storage usage by the following: Topic Partition Instance Client With the help of this, we can identify which resource is utilizing more storage, and understand the resource utilization pattern. When creating the cluster, you provision the storage according to your needs and that storage you pay for how much storage your resources have used from this provisioned storage. By doing this, you can see which resource is consuming how much storage. Based on this information, you can decide whether to keep that resource or not. Since the MSK cluster is a pay-for-what-you-use model, We can find how much storage usage per resource in GB-hours and in GB-months. This allows you to track the usage on a daily and monthly basis. Based on this information, we can plan for future capacity needs, scale our cluster, and optimize resource allocation. The following metrics are used: Number of Clients |Expr: count(count by(client_id) (Kafka_server_Fetch_byte_rate{client_id!~"^consumer-amazon.msk.*"})) + count(count by(client_id) (Kafka_server_Produce_byte_rate{client_id!~"^producer-.*"})) Number of Partition Number of Topics Number of Brokers Expr:sum(Kafka_controller_KafkaController_Value{name="", job="Kafka-broker", env="dev", instance=~"$instance", cluster=~"$cluster"}) Storage Used Monthly: |Expr: sum by() (rate(Kafka_log_Log_Value{name=”Size”, job=”Kafka-broker”, env=”dev”, instance=~”$instance”, topic=~”$topic”,partition=~”$partition”}[1h])) / $convert_to_GB / $GB_Month GB-hours: |Expr: sum by() (rate(Kafka_log_Log_Value{name=”Size”, job=”Kafka-broker”, env=”dev”, instance=~”$instance”, topic=~”$topic”,partition=~”$partition”}[1h])) Partition Topic Instance Tiered Storage Instance Topic Monthly: |Expr: sum by() (rate Kafka_server_BrokerTopicAggregatedMetrics_Value{name=”RemoteLogSizeBytes”, job=”Kafka-broker”, env=”dev”, instance=~”$instance”, cluster=~”$cluster”}[1h])) * $GB_Month / $convert_to_GB GB-hours: Expr: sum by() (rate(Kafka_server_BrokerTopicAggregatedMetrics_Value{name=”RemoteLogSizeBytes”, job=”Kafka-broker”, env=”dev”, instance=~”$instance”, cluster=~”$cluster”}[1h])) Cost Center In this model, We provide an estimate how much it will cost you based on the resource usage in the previous model. We will calculate the cost based on the following resources: Topic Partition Instance Client The cost of the above-mentioned resources are calculated based on the observed GB-month resource usage. This model works well for the scenarios with very high Kafka cluster utilization over long periods of time. The following metrics are used: Outbound Charges monthly Expr: sum by(instance) (rate(Kafka_server_BrokerTopicMetrics_Count{name="BytesOutPerSec", job="Kafka-broker", env="$env", cluster="$cluster"}[1m])) / $convert_to_GB / $GB_Month Storage Usage Cost monthly Client |Expr: sum by(client_id) (rate({client_id=~"$producer_client_id", job="Kafka-broker", env="dev", instance=~"$instance"}[1h])) / $convert_to_GB / $GB_Month Partition |Expr: sum by(topic, partition) (rate(Kafka_log_Log_Value{name="Size", job="Kafka-broker", env="dev", instance=~"$instance", topic=~"$topic", partition=~"$partition"}[1h])) / $convert_to_GB / $GB_Month Topic Expr: sum by(topic) (rate(Kafka_log_Log_Value{name="Size", job="Kafka-broker", env="$env", instance=~"$instance", topic=~"$topic"}[1h])) / $convert_to_GB / $GB_Month Tiered Storage Cost Topic |Expr: sum by(topic) (rate(Kafka_server_BrokerTopicAggregatedMetrics_Value{name="RemoteLogSizeBytes", job="Kafka-broker", env="dev", topic=~"$topic", instance=~"$instance"}[1h])) * $GB_Month / $convert_to_GB Instance Expr: sum by(instance) (rate(Kafka_server_BrokerTopicAggregatedMetrics_Value{name="RemoteLogSizeBytes", job="Kafka-broker", env="dev", instance=~"$instance", cluster=~"$cluster"}[1h])) * $GB_Month / $convert_to_GB Instance Charges Monthly Expr: sum by(instance) (rate(Kafka_log_Log_Value{name=”Size”, job=”Kafka-broker”, env=”dev”, instance=~”$instance”, cluster=~”$cluster”}[1h])) / $convert_to_GB / $GB_Month Conclusion In conclusion, With the help of MSK cluster, you don’t have to worry about your servers, you just need to take care about the storage usage and cost . Performing open monitoring on MSK clusters using prometheus and grafana without relying on cloudWatch metrics offers the cost-effective way to manage your Kafka cluster. This also encourages the usage of resources and provides detailed insights to the team, and accordingly they can plan their budget for further uses. To further improve this dashboard, you can include the cross-zone charges metrics in the cost center dashboard by creating the custom metrics for availability zone, and region. This will help you to optimize your Kafka cluster even further. --- # Automating Kafka Deployments with CI/CD URL: https://platformatory.io/blog/Automating-Kafka-Deployments-with-CICD/ Published: 2024-08-13 Authors: Vikhyat Shetty Categories: Kafka, DevOps, CI/CD, Kafka Operations Automating Kafka Deployments with CI/CD Deploying Kafka, whether the open-source version or Confluent Platform, presents a myriad of challenges like managing dependencies and ensuring compatibility to handling scaling and fault tolerance, the process can be intricate and time-consuming. This blog delves into the current deployment options for Kafka, the challenges faced, and how a CI/CD implementation can revolutionize your deployment strategy. Current Kafka Deployment Options We won’t cover manual deployments since they aren’t typically used in production environments. Instead, there are two main methods for deploying Kafka: Ansible: Ansible automates Kafka deployment through the use of playbooks, which are YAML files defining the deployment process. By leveraging the Ansible you can configure, deploy, and manage Kafka clusters with minimal manual intervention. Ansible’s agentless architecture allows it to work seamlessly across different environments, making it a flexible and reliable option for managing Kafka deployments. Kubernetes: Deploying Kafka on Kubernetes allows you to leverage container orchestration, providing scalability, fault tolerance, and ease of management. Kubernetes can manage the entire lifecycle of Kafka clusters, from deployment and scaling to upgrades and failure recovery. Tools like Strimzi or the Confluent Operator can be used to simplify the deployment and management of Kafka on Kubernetes. Deploying Kafka or the Confluent Platform is a multifaceted process that requires careful planning, configuration, and ongoing management to ensure optimal performance and reliability. The complexity arises from the need to balance various factors such as hardware requirements, security, data management, monitoring, and scaling. Expertise and continuous attention to detail are crucial for successful deployments. Challenges in Kafka Deployment Ansible deployed clusters Requires familiarity with Ansible and its configuration. Playbooks might need adjustments for complex or non-standard setups. And Kubernetes, Requires a Kubernetes environment and knowledge of Kubernetes operations. Initial setup and configuration might be complex for those unfamiliar with Kubernetes. How CI/CD can work for Kafka Deployment Implementing Continuous Integration and Continuous Deployment (CI/CD) for Kafka offers several benefits: Single Source of Truth: Centralized configuration management ensures consistency across environments. Administrator-Regulated Using Version Control: Changes are tracked, audited, and managed through version control systems like Git, enhancing security and compliance. Ease of Rolling Updates: Automated deployment pipelines facilitate seamless updates and reduce the risk of human errors. One-Push Mechanism: Simplified deployment process through a user-friendly interface, eliminating the need for in-depth Kafka expertise. In comes kafka-cp-deploy-manager This is the solution we’ve devised, called kafka-cp-deploy-manager. It aims to address some of the limitations in existing solutions, which will be discussed later in this blog. Managing Kafka clusters can be challenging, with tasks like version upgrades, configuration changes, and scaling to meet demand requiring careful coordination. The kafka-cp-deploy-manager streamlines this process by managing the state of Kafka clusters and automating deployments to reach the desired configuration. We’ve built a pre-configured pipeline using Confluent’s Ansible-based deployment solution for Kafka, enhancing its usability. This tool allows us to create deployment pipelines for other methods like open-source Apache Kafka and Confluent for Kubernetes (CFK). How It Works kafka-cp-deploy-manager works alongside Jenkins for continuous deployment on any state changes. Jenkins abstracts away the deployment complexity by providing simplified configurable variables in an interactive UI. This integration ensures that any state changes are deployed consistently and reproducibly, mitigating human error. Sample Configuration To illustrate the effectiveness of kafka-cp-deploy-manager, let’s look at a sample configuration. We can use a yaml file like this to set up custom pipelines. Here’s what you need to set up: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 all: vars: ansible_connection: ssh ansible_user: root ansible_become: true ansible_ssh_private_key_file: /path/to/private-key git_repository_url: "artifacts_repo_url" git_token: "token" jenkins: hosts: hostname: vars: pipeline: "pipeline_name" environment: JENKINS_HOME: /data/jenkins jenkins_agent: hosts: hostname: vars: collections: /path/to/confluent_files.jar artifacts_repo_url: The repository containing the artifacts. token: To access the Git repository. pipeline_name: The pipeline that needs to be run. /path/to/confluent_files.jar: Specifies where the necessary jar files are located. These configurations enable users to manage their Kafka clusters effectively with a simple, configurable interface without requiring an in-depth understanding of Kafka. Example Scenario: Let us see how easily we can upgrade the confluent platform using kafka-cp-deploy-manager Upgrading Kafka with kafka-cp-deploy-manager We have a Confluent Platform version 7.4.3 installed on an EC2 instance. Now, we will upgrade Kafka to version 7.5.3. Check the current version of Confluent Platform Access the Ansible Install Pipeline: Navigate to the pipeline dashboard. Add Required Parameters: URL of Git Repository: Provide the repository URL. Git Repo Access Token: Input the access token. Branch: Specify the branch for the new version. Confluent Platform Version: Set to 7.5.3. Private Key of EC2 Instance: Provide the private key for the instance. Trigger the Build: Click on ‘Build’ to run the pipeline. Monitor the Console Output: Watch the pipeline run in the console output. Verify the Upgrade: Check the Confluent Platform version in the EC2 instance to ensure it has been upgraded to 7.5.3.! Conclusion kafka-cp-deploy-manager is a powerful tool that helps users manage their Kafka clusters efficiently. With its consistent and reproducible deployment pipelines, minimized human error, smooth upgrades and rollbacks, and clear separation of privileges, it simplifies Kafka cluster management. Users can achieve effective Kafka cluster management with a simple, configurable interface, making the process accessible even without deep Kafka knowledge. Key Benefits Consistent and Reproducible Deployment Pipelines: Ensures that deployment pipelines are consistent, reducing the chances of errors and inconsistencies. Mitigates Human Error: By automating the deployment process, it minimizes human error, making the process more reliable. Smooth Upgrades and Rollbacks: Version changes to the state file are easily managed, ensuring smooth upgrades and rollbacks. Isolation Between Write and Execute Privileges: Admins can create or modify state files, while developers can trigger the deployment process, ensuring clear separation of responsibilities. --- # Querying Stream Processing Systems (Apache Flink) URL: https://platformatory.io/blog/querying-state-store-in-apache-flink/ Published: 2024-08-11 Authors: Avinash Upadhyaya Categories: Apache Flink, Stream Processing, Kafka Streams Background Traditionally, there are 2 categories of data inside most organizations. The Operational Data that the systems use for running the business is stored in databases, and the Analytical Data that the systems use for generating insights is stored in buckets. The data from the operational estate is moved over to the analytical estate with some data engineering techniques, either in batches or through streams in real time while processing and transforming the data. These worlds of Operational and Analytical data intersect but are largely independent and maintained by separate teams. However, in recent times, there has been a lot of convergence between the two data world views. For example, if a SaaS application uses Machine Learning to generate an insight based on the user activity and provide this to the user, it involves data in both the data estates since it involves solving for the business use case and generating analytics. This is a common pattern emerging, where the data moves only from the Operational plane to the Analytical plane but in the other direction as well. This can be a result of machine learning models or real-time data processing in general. Stream processing systems such as Kafka Streams or Apache Flink fit in this kind of architecture. Stream processing works on data in motion, and therefore it is perennially in transit. Stream processing probably is in both data world views, i.e., in the Operational estate and the Analytical estate, depending on the context. If the stream processor computes an aggregate for an user and does event sourcing, or CQRS, it can be labeled as Operational data. But if that data is ingested into an RTOLAP database or running stream processing jobs to generate insights, it can be classified as Analytical data, where it has no immediate business impact. Another interesting worldview that has emerged recently is the concept of a streaming data plane. This implies the state of the data as when it is in transit and potentially being processed. Most stream processing systems do not allow to talk directly to the stream processing system because the notion of consistency in stream processing is different from the database world. The stream processor would write the results to a sink after processing, which is where the data is accessible. This is the streaming data plane, where the streaming data plane talks to you and not the other way around. Querying the stream processing system Thus began the idea of being able to talk to the stream processing system directly instead of having an additional hop of an external data store where the data is sinked into. This meant talking to the state backend, usually in memory or an embedded database like RocksDB. This is a popular pattern that has emerged. In Kafka Streams, one of the interesting features is the ability to interactively query the state stores. This is implemented through RPCs and knowledge of where a particular key is stored in a distributed Kafka Streams application. This essentially results in a distributed database, which can be purpose built for unique use cases. When Kafka Streams is embedded in an application, this pattern results in a distributed database embedded in the application supporting various use cases without having to use an additional system like Redis or Memcache. Querying the state store in Apache Flink Although Kafka Streams provides the ability to query the state store interactively, Kafka Streams is a library rather than a complete stream processing system that lacks a few important concerns for a stream processing system. Apache Flink has resource management as a first class concern, along with the ability to snapshot the state regularly for disaster recovery. Apache Flink is the most comprehensive unified processing system with first class streaming and batch processing. It supports a wide range of connectors while providing exactly once consistency guarantees. All of these make Flink the standard for stream processing. Interactively querying the state store in Apache Flink involves the intersection of three different subsystems - QueryableStateClient - The client responsible for querying the Flink state store for a particular key in a job. The QueryableStateClient talks to any task manager for querying the state. QueryableStateClientProxy - A server side component that is responsible for talking to the job manager and understanding where the queried key is located since Flink is a distributed system where the state is distributed among multiple task managers. The job manager does the bookkeeping of where a particular key group lies and which task slot it is scheduled to. The QueryableStateClientProxy resides in all task managers. QueryableStateServer - The QueryableStateServer is responsible for serving the query from the state store after the state store is determined by the QueryableStateClientProxy. All of the state data is retrieved from the Flink state store without the need for the data to be sinked to an additional data store. Queryable State Store in Apache Flink By default, the state stores in Apache Flink are not queryable. The state stores need to be explicitly marked as queryable for running interactive queries on them. There are 2 approaches to doing this - QueryableStateStream - A convenience object that acts as a sink and offers its incoming values as a queryable state. setQueryable - stateDescriptor.setQueryable(String queryableStateName) makes the keyed state represented by the state descriptor, queryable. The Flink distribution will also require the flink-queryable-state-runtime dependency for querying the state stores. The property queryable-state.enable needs to be set to true in the Flink configuration. Query Client Implementation 1 2 3 4 5 6 7 QueryableStateClient client = new QueryableStateClient(tmHostname, proxyPort); CompletableFuture getKvState( JobID jobId, String queryableStateName, K key, TypeInformation keyTypeInfo, StateDescriptor stateDescriptor) The getKvState method returns a CompletableFuture eventually holding the state value for the queryable state instance identified by queryableStateName of the job with ID jobID. The key is the key whose state you are interested in, and the keyTypeInfo will tell Flink how to serialize/deserialize it. The stateDescriptor contains the necessary information about the requested state, namely its type (Value, Reduce, etc.) and the necessary information on how to serialize/deserialize it. The returned future contains a value of type S, i.e., a State object containing the actual value. This can be any of the state types supported by Flink: ValueState, ReduceState, ListState, MapState, and AggregatingState. The client is asynchronous and can be shared by multiple threads. It needs to be shutdown via QueryableStateClient.shutdown() when unused in order to free resources. Important gotchas These state objects do not allow modifications to the contained state. You can use them to get the actual value of the state, e.g., using valueState.get(), or iterate over the contained entries, e.g., using the mapState.entries(), but you cannot modify them. As an example, calling the add() method on a returned list state will throw an UnsupportedOperationException. When querying a state object, that object is accessed from a concurrent thread without any synchronization or copying. This is a design choice, as any of the above would lead to increased job latency, which we wanted to avoid. Since any state backend using Java heap space, e.g., HashMapStateBackend, does not work with copies when retrieving values but instead directly references the stored values, read-modify-write patterns are unsafe and may cause the queryable state server to fail due to concurrent modifications. The EmbeddedRocksDBStateBackend is safe from these issues. Scaling Scaling the queryable state server and client involves tuning the following configurations - queryable-state.server.network-threads: number of network (event loop) threads receiving incoming requests for the state server (0 implies the number of task slots). queryable-state.server.query-threads: number of threads handling/serving incoming requests for the state server (0 implies the number of task slots). queryable-state.proxy.network-threads: number of network (event loop) threads receiving incoming requests for the client proxy (0 implies the number of task slots). queryable-state.proxy.query-threads: number of threads handling/serving incoming requests for the client proxy (0 implies the number of task slots). Real world usage New Relic uses the queryable state store in Apache Flink to replace solutions such as Redis for querying the aggregated golden signals directly from Apache Flink. Relative to using Redis for this use case, New Relic observed that the queryable state store solution was 97% cheaper at the scale New Relic operates at, which is about 71 million golden metrics per minute. The talk from New Relic at Flink Forward 2022 discusses this in depth and the benefits they achieved. Other scenarios where the queryable state store might be useful is for a look aside cache scenario, potentially in the gaming industry where many clients have to be handled for a bunch of metrics. Conclusion The Queryable State Store feature in Apache Flink is no longer maintained due to a lack of maintainers. However, it is still available as part of new releases. This is still possible and actively maintained in Kafka Streams if that fits the bill. Another category of systems to explore is the streaming databases, which also resides in the streaming data plane. The main difference between streaming databases and a data flow oriented system like Flink is that Flink has control over the data flow. In the future, it is possible that many databases will provide such capabilities directly in the database, including stateful stream processing and UDF support; Aka return to materializedViews++. For an implementation of the queryable state store, refer to the GitHub repository for a proof of concept. The feature is extremely useful in low latency scenarios, saving an additional hop. However, it is prone to shuffles and should usually be augmented by a caching layer. This puts Flink in the operational land but might raise concerns over managing a ton of socker connections asking for “live data”; possibly solved with a push layer. --- # Integrating APIs and Event Streaming: for fun and profit URL: https://platformatory.io/blog/how-to-turn-your-legacy-architecture-to-an-event-driven-system/ Published: 2024-08-04 Authors: Avinash Upadhyaya Categories: Event-Driven Architecture, Kafka, Real-time How to turn your legacy architecture to an event-driven system In the world of microservices and real-time applications, event-driven architecture is widely adopted for building loosely coupled systems. As a result of this, multiple patterns have emerged, such as Event Notifications, Event Sourcing, CQRS, etc. All of these patterns depend on the system’s ability to produce events and react to events in a timely manner. But what are these events, and why are they important? An event is a statement of something happening, implying a change in state. Events are indicative of something happening in real life, such as an order being placed, a customer signing up, etc., or events can be a system change as well. Adopting an event-based architecture has immense benefits, including the ability to build loosely coupled, independently scalable services, and immutable events help as a source of truth over time. Adopting event-driven architecture comes with its fair share of challenges and increased complexity. Request-Response When an event occurs, there will be multiple stakeholders interested in consuming and acting upon those events. Most popular APIs are today built on the request-response paradigm. These are implemented using HTTP and work well, but only for a client-server model. There are requests that mutate the state of a resource, i.e., in a REST context, POST, PUT, and DELETE requests. For example, when an order is created, the payment is processed, a bank transaction is made, etc. These requests have to update transactional databases, sometimes multiple databases. This is a time-consuming orchestration and makes these types of APIs difficult to scale sub-linearly with increased load. Messaging In contrast to a request-response approach, a messaging-driven approach can solve for scale. In this approach, services send events to a high-performance message or event broker like Apache Kafka, which then fans them out to multiple subscribed services. This scales well because it is not dependent on the consuming service for a response. The message broker acts as a buffer for increased loads and allows multiple interested parties to consume. However, this lacks transactional semantics and is often difficult to implement. Request-Response + Messaging An ideal solution for most use cases may require a combination of both approaches. This implies that the service receiving the request performs a dual write to the database and to a message broker. Another approach is to propagate changes made to the database through a message broker using techniques such as Change Data Capture (CDC). These approaches, however, suffer from one of the two limitations Dual writes are complicated to achieve and require sensitive code changes. Many times, these may be legacy applications or outside our domain of control. Approaches such as CDC capture row-level changes, but piecing back domain objects from tables and row-level changes requires a lot of complex stream processing. Eventception - Reflexive events at scale And this is specifically what Eventception solves for. It does this by treating the API history as a transactional log. It integrates directly with most API platforms, gateways, and proxies in near real time and allows you to synthesize these into self-evident events using an interactive model or declarative annotations embedded directly in your interface description, such as in your OpenAPI3 specification. The result is what we call reflexive events consumable through the Kafka protocol, Kafka connectors, or webhooks that call your endpoints. All this requires zero code changes in your application. And unlike CDC, your APIs target the fully formed domain object as a resource, so therefore there are minimal processing overheads. Here’s how Eventception works with an API Gateway to generate events - Eventception integrates with the most popular API gateways, such as Kong, AWS API Gateway, and Istio (Envoy), to discover APIs. API logs are then collected, either through a push mechanism to Eventception’s Kafka or pull from an existing log source such as Kafka, S3, or ElasticSearch. The processors for defining the criteria and shape of the desired events are defined using CEL and JSONata that are embedded in the OpenAPI specification, which is then uploaded to Eventception. Eventception parses these processor rules and processes the raw API logs into streams of desired events. Change Data Capture can be enabled on these streams. Finally, the streams can be consumed through various consumers - Kafka consumers, S3 connectors, database connectors, or webhook calls. To know more about how Eventception works, take a look at the demo video. Use cases Resource Topics and Changelogs (CDC) at the API level Eventception allows creation of a resource topic per domain resource at an endpoint level, along with schema inference using the OpenAPI specification. Furthermore, change data for each resource can be captured at the API level. For example, a resource topic can be created for “orders” by creating a stream for the “/orders” endpoint and enabling Change Data Capture for the stream. Transactional Processing Multi-resource sagas A typical transaction spans across multiple services, affecting multiple databases / resources. Eventception allows building processing workflows (sagas) for such multi-resource transactions by acting as an event store and generating events in a desired format to a desired sink. For example, when an order is placed or updated, the order resource and several line items are affected. The two services need to be correlated for a particular order ID, and a workflow needs to be executed. Eventception helps with achieving this by presenting the two events in a desired format after all processing and in a common sink. Generic Event Processing and fan-out to services Another common use case for Eventception is to parse, pre-aggregate, and filter data using an idiomatic DSL (including IDL level integration for different API styles) so as to summarize, roll-up, and efficiently manage massive volumes of data over time. For data-intensive applications, it could be used primarily as a data exchange and fanout mechanism between systems. It could be used to send operational data to real-time analytical databases or to data lakes and warehouses. This is achieved through connectors, consumers, and webhooks in Eventception. Hydrate an Event-Store = Aggregates, Event-sourcing, CQRS Eventception is an ideal platform for Event sourcing and CQRS in a polyglot world. It could be used to source events directly through a proxy data plane such as Envoy and automatically sync synthesized events to an event store through a connector. It can also potentially perform processing to go build projections, Materialized Views, or even warm caches. Stand to audit Eventception can be used to ingest events from common L4-L7 proxies, network logging appliances, or existing syslog agents. This acts as an audit of events that have happened over time and can be sent to stores such as DuckDB for fast querying. Eventception also acts as an audit trail of API events, including changes made to API resources over time using CDC. Accelerate the API In several scenarios, the API service might have to perform complex processing or depend on asynchronous requests for processing the API. In such cases, Eventception can be used to implement request-reply / reply-later / async-await / webhooks patterns, where the response is sent asynchronously through webhook calls or through a Kafka message, all without any custom code. Conclusion Evolving to event-driven architecture can be challenging, but Eventception vastly simplifies this by providing an external layer for generating and processing events without having to write custom code.    Eventception also provides you a rich set of metrics as well as APIs to process dead letter channels. --- # Comparison of Kafka Deployment Options on Kubernetes URL: https://platformatory.io/blog/kafka-on-kubernetes/ Published: 2024-08-02 Authors: Raghavendran Nehru Categories: Kafka, Kubernetes, Platform Engineering, Infrastructure Introduction Kubernetes (or K8S) is an open source system for automating deployment, scaling and management of containerized applications. It was originally developed by Google, inspired from their experience of deploying scalable, reliable systems in containers via application-oriented APIs. Since its introduction in 2014, Kubernetes has grown to be one of the largest and most popular open source projects in the world. It has become the standard API for building cloud native applications, present in nearly every public cloud. Apache Kafka is a distributed streaming platform that is used as a backbone for an organization’s data infrastructure. So, organizations that build, deploy, manage/operate cloud native applications look at running Kafka on K8S to take advantage of everything that K8S offers (scaling, recovery from failures, optimal use of resources). Key Characteristics of Kafka Based on the release timeline (Zookeeper 3.0 released in 2008, Kafka released in 2011, Docker in 2013 and Kubernetes in 2014), Kafka (and in turn Zookeeper) predate native container based applications. So, they fall into the category of applications that are containerized though they were not built to be run in containers. Also, we need to make them Stateful (brokers store data into files and cache the data in the filessytem cache), have the producers/consumers know the existence of brokers, have the ability for each broker to connect to others, and be able to recover back after a pod goes down (a pod in Kubernetes consists of one/more containers that work together to offer a set of features. One design option is to containerize Kafka/Zookeeper and build each one into a pod which can then be handled by Kubernetes). flowchart TD subgraph PRODUCERS["Producers"] P1("Producer 1") P2("Producer 2") P3("Producer 3") end subgraph CG1["Consumer Group 1"] C1("Consumer 1") end subgraph CG2["Consumer Group 2"] C2("Consumer 1") C3("Consumer 2") end subgraph CG3["Consumer Group 3"] C4("Consumer 1") C5("Consumer 2") end subgraph K1["Kafka Cluster"] B1["Broker 1"] B2["Broker 2"] B3["Broker 3"] end subgraph Z1["Zookeeper Cluster"] direction TB ZK1["Zookeeper Node 1"] ZK2["Zookeeper Node 2"] ZK3["Zookeeper Node 3"] end ZK1 <--> B1 ZK2 <--> B1 ZK3 <--> B1 ZK1 <--> B2 ZK2 <--> B2 ZK3 <--> B2 ZK1 <--> B3 ZK2 <--> B3 ZK3 <--> B3 ZK1 <--> ZK2 <--> ZK3 P1 -- Produces ---> B1 P2 -- Produces ---> B2 P3 -- Produces ---> B3 B1 -- Consumes --> CG1 B2 -- Consumes --> C2 B3 -- Consumes --> C3 B2 -- Consumes --> C5 B3 -- Consumes --> C4 %% Styling classDef kafkaStyle fill:#e0f7e9,stroke:#4caf50,stroke-width:2px; class K1,K2 kafkaStyle; Typical Requirements of running Kafka Security Auto generate certificates for TLS and mTLS between brokers and other internal components Natively support authentication mechanism such as SASL/PLAIN, SASL/SCRAM, SASL/OAUTHBEARER, SASL/GSSAPI Authorization with ACLs - Provide user management capabilities using the k8s API Operations Re-balancing partitions when the load on the brokers is uneven, broker is added/removed Monitoring cluster health with JMX metrics Rolling upgrades with no downtime Replicate data across clusters Rack awareness for durability How do we model the Kafka/Zookeeper Resources? Kubernetes supports several native resources to manage and orchestrate containers. Some of them are Pods, Nodes, Namespaces, ReplicationController, ReplicaSet, StatefulSets, Services, Endpoints, ConfigMaps, Secrets, PersistentVolumes, PersistentVolumeClaims, Ingress, Custom Resource Definitions (CRDs) and Roles/RoleBindings among others. So, what we see is that Kafka related resources are not natively supported. But, Kubernetes provides extensibility via CRDs to model a cluster, Connect/Connector, Mirror Maker (to replicate records across Kafka clusters), Kafka Users, Topics, Prometheus Metric, and Security (TLS, SCRAM, Keycloak). How do we model the infrastructure? * StatefulSet* : a StatefulSet is a Kubernetes resource designed for stateful applications. So, we can model both Kafka/Zookeeper as a StatefulSet which guarantees: Stable, unique names and network identifiers Stable persistent storage that moves with the pod (even when it moves to a different node) Pods are created sequentially (1, 2, 3, … n) and terminated in the opposite order (n, n-1, …, 3, 2, 1) Rolling updates are applied in the termination order All successors of a pod should be terminated before the pod itself is terminated A StatefulSet requires a ** headless service ** to control the domain of the pods. A normal service presents an IP address and load balances the pods behind it, but a headless service returns the IP addresses of all its pods in response to a DNS query. Due to this, Kubernetes allows DNS queries for the pod name as part of the service domain name. An interesting question arises about how a producer/consumer outside of the Kubernetes cluster gets access to the pods (Kafka Brokers). In case they are all within the same network, connectivity works seamlessly. If not, then there is a need to implement a Container Network Interface (CNI) which is part of the plumbing offered by Kubernetes to create an application (along with Container Runtime Interface or CRI and Container Storage Interface or CSI). Some downsides to using a StatefulSet: Broker configuration cannot be modified, unless specific override mechanisms are implemented (e.g., initContainers) Cannot remove a specific broker because it allows the removal of most recently added broker (based on the termination order in a StatefulSet) Cannot use different persistent volumes for each broker How do we take care of Resource Management? Kubernetes provides a pattern called the Operator. Any complex stateful workload (like Kafka) that can’t be run as a fully managed service can be provided as a Kubernetes operator. This allows us to proactively manage custom resources (created via the CRDs). Operators are very powerful and they enable users to get custom abstractions that are responsible for deployment, health check and repair of the custom resources (e.g., Kafka Cluster, Topic). graph TD A[Kubernetes API Server] -->|Watches| B[Controller] B -->|Reads Desired State| C[Etcd - Cluster State Store] B -->|Reads Actual State| D[Kubernetes Resources e.g. Pods, Nodes] B -->|Reconciles| E[Adjusts Kubernetes Resources] C -->|Stores Updated State| A E -->|Updates| A Operator Components: Kubernetes API Server (A): The central management point for the cluster, providing the interface for all resource operations. Controller (B): A control loop that watches the desired state in the API Server, compares it with the actual state of resources, and takes action to reconcile the differences. Etcd (C): The key-value store where Kubernetes stores its desired state and cluster configuration. Kubernetes Resources (D): The actual state of resources (e.g., Pods, Nodes) in the cluster. Reconciliation Process (E): The controller adjusts the resources as needed to align the actual state with the desired state stored in etcd. Extending the Operator pattern to model Kafka resources could have CRDs for Topic, Kafka Cluster, Zookeeper. The Controllers: Kafka Operator and Zookeeper Operator read the CRDs, create the resources and run reconciliation loops to maintain the desired state. flowchart TD subgraph KubernetesCluster["Kubernetes Cluster"] direction TB subgraph Controllers["Controllers"] KOperator["Kafka Operator"] ZOperator["Zookeeper Operator"] end subgraph KafkaResources["Kafka Resources"] KafkaCluster["Kafka Cluster"] ZookeeperCluster["Zookeeper Cluster"] KafkaTopics["Kafka Topics"] end subgraph ManagedResources["Managed Resources"] Brokers["Kafka Brokers"] ZKNodes["Zookeeper Nodes"] end subgraph CustomResources["Custom Resources"] KCR["Kafka Custom Resource"] ZKCR["Zookeeper Custom Resource"] TopicCR["Kafka Topic Custom Resource"] end end KOperator --> KafkaCluster ZOperator --> ZookeeperCluster KOperator --> KafkaTopics KOperator --> Brokers ZOperator --> ZKNodes KCR --> KOperator ZKCR --> ZOperator TopicCR --> KOperator Brokers -- depends on --> ZKNodes KafkaCluster -- managed by --> KOperator ZookeeperCluster -- managed by --> ZOperator %% Styling classDef kafkaStyle fill:#e0f7e9,stroke:#4caf50,stroke-width:2px; class K1,K2 kafkaStyle; classDef default font-size:16px; Scope of coverage: A mental model on Kubernetes Operators for Kafka What are the important requirements from an Operator to successfully run Kafka on Kubernetes? We list them here: Operator Core Custom Resources Workload Type Networking Storage Security Authentication Authorization Operational Features Balancing Monitoring Disaster Recovery Scale up/out Deployments & Rollouts Extensibility It is really hard to get deep into K8S, model the Kafka resources and implement the Operator pattern to have a production ready system that can achieve the objectives. But, there is help! Deployment Options to run Kafka on K8S Strimzi Strimzi is an open-source project designed to run Apache Kafka on Kubernetes. It simplifies the deployment, management, and monitoring of Kafka clusters. Features: Automated deployment and scaling of Kafka clusters. Integrated Zookeeper management. Custom resource definitions (CRDs) for Kafka, Kafka Connect, Kafka MirrorMaker, and Kafka Bridge. Configuration of Kafka resources (e.g., Kafka cluster - Storage, Listeners, Rack awareness) Rolling updates and upgrades. Monitoring and logging with Prometheus and Grafana. Implement security in a Kubernetes-native fashion Uses StrimziPodSets to overcome challenges of StatefulSets Add/remove broker arbitrarily Stretch cluster across k8s clusters Different configurations and volumes for different brokers KafkaBridge for a RESTful HTTP interface Security: FIPS mode auto-enablement when using Strimzi container images flowchart LR subgraph K1["Kafka Cluster"] subgraph P1B1["Pod 1"] B1["Broker 1"] end subgraph P2B2["Pod 2"] B2["Broker 2"] end subgraph P3B3["Pod 3"] B3["Broker 3"] end end subgraph EO["Entity Operator"] UO["User Operator"] TO["Topic Operator"] CO["Cluster Operator"] end subgraph KCO[" "] K1 EO end subgraph SZ["Strimzi"] KCO TCR CO UCR KCR end subgraph KC["Kubernetes Cluster"] SZ end KCO <--> CO <-- Deploys & Manages --> K1 TO <--> TCR["Topic Custom Resources"] UO <--> UCR["User Custom Resources"] CO <--> KCR["Kafka Custom Resources"] TO -- Manages Topics --> K1 UO -- Manages Users --> K1 %% Styling classDef kafkaStyle fill:#e0f7e9,stroke:#4caf50,stroke-width:2px; class K1,K2 kafkaStyle; classDef default font-size:16px; Confluent for Kubernetes (CFK) Confluent for Kubernetes is a Confluent-supported operator for deploying and managing Confluent Platform components, including Kafka, on Kubernetes. This was developed based on Confluent’s experience of developing Confluent Cloud using Kubernetes. Please refer to the Kora engine paper for more details. Features: Automated deployment and scaling of Confluent Platform components. Advanced security configurations, including TLS, Kerberos, and OAuth. Integration with Confluent Control Center for monitoring and management. Uses StatefulSets for restoring a Kafka pod with the same Kafka broker ID, configuration, and persistent storage volumes if a failure occurs. Provides server properties, JVM, and Log4j configuration overrides for customization of all Confluent Platform components. Complete granular RBAC Support for credential management systems, via CredentialStoreConfig CR, to inject sensitive configurations in memory to Confluent deployments Supports tiered storage Supports multi-region flowchart TB subgraph K1["Kafka Cluster"] direction LR subgraph P1B1["Pod B1"] B1["Broker 1"] end subgraph P2B2["Pod B2"] B2["Broker 2"] end subgraph P3B3["Pod B3"] B3["Broker 3"] end end subgraph ZK1["Zookeeper Cluster"] subgraph P1Z1["Pod 1"] Z1["Node 1"] end subgraph P2Z2["Pod 2"] Z2["Node 2"] end subgraph P3Z3["Pod 3"] Z3["Node 3"] end end subgraph CC1["Connect Cluster"] subgraph P1C1["Pod 1"] CW1["Node 1"] end subgraph P2C2["Pod 2"] CW2["Node 2"] end subgraph P3C3["Pod 3"] CW3["Node 3"] end end subgraph SR1["Schema Registry"] subgraph P1SR1["Pod 1"] SRN1["Node 1"] end subgraph P2SR2["Pod 2"] SRN2["Node 2"] end end subgraph R1["Replicator"] subgraph P1REP1["Pod 1"] REP1["Replicator 1"] end subgraph P2REP2["Pod 2"] REP2["Replicator 2"] end end subgraph COCP["Control Center Pod"] COCE["Control Center"] end subgraph O["Operator Pod"] OP1["Operator"] end subgraph KR["Kafka Resources"] K1 ZK1 CC1 COCP SR1 R1 end subgraph KC["Kubernetes Cluster"] O KR CLS end subgraph PSV["Persistent Storage Volumes"] AEBS["Amazon EBS"] GCPS["GCP Storage"] AD["Azure Disks"] RS["Remote Storage"] end subgraph RP["Resource Provider (AWS, GCP, Azure, OpenShift)"] KC PSV end %% Connections O --|Manages|--> KR KR -->|Uses| AEBS KR -->|Uses| GCPS KR -->|Uses| AD KR -->|Uses| RS %% Styling classDef kafkaStyle fill:#e0f7e9,stroke:#4caf50,stroke-width:2px; class K1,K2 kafkaStyle; classDef default font-size:16px; KOperator (formerly Banzai Cloud Kafka Operator) KOperator, developed by Banzai Cloud (now part of Cisco), provides a robust and scalable solution for running Kafka on Kubernetes. Features: Uses pods instead of StatefulSets, in order to ConfigMaps: modify the configuration of unique Brokers. Rack awareness. Storage: use multiple Persistent Volumes for each Broker Envoy based load balancing for external access CruiseControl for scaling up/down, rebalance Orchestration: remove specific Brokers from clusters Self-healing and automated recovery. Integrated Zookeeper management. Monitoring with Prometheus and Grafana. Multi-cluster support and cross-cluster replication. flowchart TD subgraph K1["Kafka Cluster"] subgraph P1B1["Pod 1"] B1["Broker 1"] end subgraph P2B2["Pod 2"] B2["Broker 2"] end subgraph P3B3["Pod 3"] B3["Broker 3"] end end subgraph CC["Cruise Control"] end subgraph KAS["Kubernetes API Server"] end subgraph PS["Prometheus"] A["Alerts"] end subgraph KO["KOperator"] AM["Alert Manager"] end subgraph KC["Kubernetes Cluster"] KO KAS CC K1 PS G TCR UCR KCR CCO end KAS --> P1B1 KAS --> P2B2 KAS --> P3B3 A --> AM PS --> G["Grafana"] P1B1 --> PS P2B2 --> PS P3B3 --> PS KO <--> KAS KO --> CC KO <--> TCR["Topic Custom Resources"] KO <--> UCR["User Custom Resources"] KO <--> KCR["Kafka Custom Resources"] KO <--> CCO["Cruise Control Operation"] %% Styling classDef kafkaStyle fill:#e0f7e9,stroke:#4caf50,stroke-width:2px; class K1,K2 kafkaStyle; classDef default font-size:16px; Feature Comparison Operator Core   CFK Strimzi KOperator Workload Type StatefulSet StrimziPodSet Pod CRs supported ClusterLink ConfluentRoleBinding Connector Connect ControlCenter KafkaRestClass KafkaRestProxy Kafka KafkaBridge KafkaConnector KafkaUser KafkaMirrorMaker2 KafkaCluster KafkaTopic KafkaUser CruiseControlOperation Networking Models Loadbalancer NodePort Ingress Loadbalancer NodePort Ingress Loadbalancer (envoy or Istio ingress) NodePort Ingress Storage * Supports Tiered Storage * Generic CSI with PVs Generic CSI with PVs Security   CFK Strimzi KOperator mTLS (with auto provisioning of certificates) Yes Yes Yes with Istio SASL/PLAIN (with k8s secrets) Yes Yes No SASL/PLAIN (with volume mounts) Yes Yes No SASL/PLAIN (with LDAP) Yes No No SASL/SCRAM-SHA-* No Yes No SASL/OAUTHBEARER No Yes No SASL/GSSAPI No No No Kubernetes RBAC No No Yes with K8S namespaces and SA Authorization   CFK Strimzi KOperator ACL Yes Yes Yes with Envoy RBAC Yes No No Security   CFK Strimzi KOperator Self balancing Automatic Self Balancing Cruise Control Cruise Control Monitoring add-ons Control Center, Confluent Health+, JMX JMX, Cruise Control JMX, Cruise Control Disaster recovery Replicator, ClusterLink. Also support Multi-region clusters MirrorMaker2 MirrorMaker2 Scale up/out kubectl scale with Self Balancing Non-broker components - K8S HPA and KEDA. Broker - Manual scaling with Strimzi Drain Cleaner Autoscaling with Cruise Control Summary Running Kafka on K8S can be a lot of toil, without an operator. You can make a choice based on your environment, features, licensing and other specialized purposes. Each operator has its own opinion based on the realities it was designed for. Kafka is ultimately not “k8s native”. The operator only provides so much operational sugar As a result, there are several shoehorning mechanisms (such as config overrides to inject component properties, builtin); Full expressivity of the workload doesn’t quite exist All operators provide comparable performance. Preferably, package all the resources in a higher order Helm chart with GitOps style deployments. --- # From Code to Cluster: Simplifying Infrastructure with IaC and Kafka URL: https://platformatory.io/blog/Simplifying-Infrastructure-with-IaC-and-Kafka/ Published: 2024-08-02 Authors: Shivaprakash Akki Categories: Kafka, Infrastructure as Code, DevOps, Kafka Operations Introduction In today’s tech landscape, managing and scaling infrastructure efficiently is essential. Infrastructure as Code (IaC) tools like Julie Ops, Terraform and Pulumi offer a streamlined way to automate infrastructure provisioning, ensuring consistency and reducing human error. Apache Kafka, a robust real-time data streaming platform, powers many modern data architectures but managing its components—brokers, topics, connectors—can be complex. This blog will show you how IaC simplifies Kafka infrastructure management. We’ll highlight key Kafka components and explore how tools like Julie Ops, Terraform, and Pulumi can make configuring and maintaining Kafka resources easier. Whether you’re a developer seeking more control or an organization looking for efficient infrastructure management, this guide offers valuable insights into leveraging IaC for Kafka. Why Infrastructure as Code (IaC)? Infrastructure as Code (IaC) is crucial for organizations because it simplifies the creation and management of resources needed for your applications. As your infrastructure grows, IaC can save engineers time and effort by automating the provisioning and configuration of resources, allowing them to focus on more complex tasks. So, what exactly is IaC? It means defining your infrastructure through code. Whenever you need to make changes or add new resources, you modify the code, and the IaC tool will handle the configuration and deployment of those resources automatically. How Infrastructure as Code (IaC) Solves Key Challenges Challenges Manual provisioning often leads to errors, and managing resources across multiple environments can be complex. Keeping configurations accurate and up-to-date is challenging. The Solution: Infrastructure as Code (IaC) IaC resolves these issues by using code to manage and provision infrastructure consistently. It offers several advantages: Faster Provisioning: Automates setup and configuration, accelerating the process. Reduced Human Error: Minimizes manual work, decreasing the likelihood of mistakes. Idempotency: Ensures consistent infrastructure setup, even if the code is executed multiple times. Fewer Configuration Steps: Consolidates all configuration tasks into code, reducing manual setup and errors. Elimination of Configuration Drift: Maintains consistency across environments and prevents discrepancies. Tools like Terraform, Pulumi, and JulieOps are popular for automating these tasks, simplifying infrastructure management. IaC Tools for Kafka Using IaC tools to configure and manage Kafka infrastructure can significantly simplify the process. Tools like Julie Ops, Terraform, and Pulumi can be used to automate the setup of Kafka components such as topics, connectors, and more. Here’s how they help: Julie Ops: Focuses on managing Kafka configurations using GitOps principles. Terraform: Provides a declarative approach to infrastructure management, allowing you to define Kafka resources in code. Pulumi: Uses programming languages like TypeScript/JavaScript, Python, Go, C#/.NET, and Java to define and manage infrastructure, offering flexibility in configuring Kafka components. JulieOps JulieOps, formally known as Kafka Topology Builder, is an open source project licensed under MIT License. It has over 400+ stars on github. It simplifies the configuration of topics, role-based access control (RBAC), Schema Registry, and other components listed in the Features of IaC Tools section. JulieOps is based on declarative programming principles, which means that developers can specify what is needed, and the tool takes care of the implementation details. The interface of JulieOps is a YAML file, which is user friendly and easy to create/update. With JulieOps, developers can easily describe their configuration requirements and delegate the rest of the work to the tool. julie-ops tool helps us to provision Kafka-related tasks in Cloud Infrastructure as a code. The related tasks are usually Topics, Access Control, Handling schemas, ksql artifacts etc. All these tasks are configured as topologies in julie-ops. Pre-Requisites Before using JulieOps to manage your Kafka configuration, ensure that JulieOps is installed locally or running in Docker. You can find the installation instructions in the JulieOps documentation. Topology File in JulieOps Here’s an example of a YAML file for defining a project-level topology with topics, schemas, KSQL artifacts, managed connectors, and principals 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 context: "contextOrg" projects: - name: "projectA" topics: - name: "topic1" config: replication.factor: "3" num.partitions: "6" - name: "topic2" config: replication.factor: "3" num.partitions: "6" schemas: - name: "schema1" type: "avro" - name: "schema2" type: "json" ksql: - name: "ksqlApp1" config: queries: - "CREATE STREAM stream1 (field1 STRING, field2 INT) WITH (KAFKA_TOPIC='topic1', VALUE_FORMAT='AVRO');" - "CREATE TABLE table1 AS SELECT field1, COUNT(*) FROM stream1 GROUP BY field1;" connectors: - name: "connector1" type: "sink" config: topics: - "topic1" tasks.max: "2" flush.size: "1000" principals: - type: "producer" name: "producer1" permissions: - "topic1:write" - type: "consumer" name: "consumer1" permissions: - "topic1:read" Kafka Client Configurations In this section, we’ll configure the necessary properties to connect to a Kafka cluster and Schema Registry using the provided credentials and settings. This setup is crucial for using tools like JulieOps to manage and interact with Kafka resources effectively. The following configuration file, named Kafka-client.properties, will set up the connection parameters for Kafka and Schema Registry, ensuring secure and authenticated communication. 1 2 3 4 5 6 7 8 9 10 11 12 bootstrap.servers="" security.protocol=SASL_SSL sasl.jaas.config=org.apache.kafka.common.security.plain.PlainLoginModule required username="" password=""; ssl.endpoint.identification.algorithm=https sasl.mechanism=PLAIN # Required for correctness in Apache Kafka clients prior to 2.6 client.dns.lookup=use_all_dns_ips # Schema Registry schema.registry.url="" basic.auth.credentials.source=USER_INFO schema.registry.basic.auth.user.info="":"" How to run The julie-ops command is used to manage Kafka resources based on a specified topology. Here’s a breakdown of the command and how to run it: Command Explanation –broker : Specifies the Kafka brokers to which Julie-Ops should connect. Replace with the actual broker addresses or connection strings. This tells Julie-Ops where your Kafka cluster is located. –clientConfig : Indicates the path to the client configuration file. This file contains the connection properties and credentials required for Julie-Ops to interact with - your Kafka cluster. Replace with the path to your actual configuration file. –topology : Defines the path to the topology file. This file contains the definitions for the Kafka topics, schemas, connectors, and other resources you want to manage. Replace with the path to your actual topology file. 1 julie-ops --broker --clientConfig --topology Once the run is completed without any errors a successful run will look like 1 2 3 4 5 6 7 8 9 10 11 log4j:WARN No appenders could be found for logger (org.apache.kafka.clients.admin.AdminClientConfig). log4j:WARN Please initialize the log4j system properly. log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info. List of Topics: List of ACLs: List of Principles: List of Connectors: List of KSQL Artifacts: Kafka Topology updated Where to Run You should run this command in an environment where Julie-Ops is installed and configured. This typically includes: Local Machine: If you have Julie-Ops installed on your local machine, you can run the command from your terminal or command prompt. CI/CD Pipeline: You can include this command in your CI/CD pipeline scripts to automate the deployment of Kafka resources as part of your build and deployment processes. Server or VM: If you’re using a dedicated server or virtual machine for managing Kafka resources, you can run the command there, ensuring that the environment has access to both Julie-Ops and the Kafka brokers. Want a quick start? checkout our sample JulieOps repo in here. Pulumi for Infrastructure as Code Choosing the right Infrastructure as Code (IaC) tool is essential, as each offers distinct benefits. While this section focuses on using Pulumi with Confluent Cloud to provision and manage Kafka Topics, Pulumi’s flexibility extends beyond cloud environments. It can be used to manage Kubernetes clusters, which can handle workloads on any infrastructure, including on-premise. Thus, while Pulumi doesn’t directly manage on-premise infrastructure like it does with cloud resources, it enables management of on-premise workloads through Kubernetes. Pulumi supports multiple programming languages, including Python, TypeScript/JavaScript, Go, C#, Java, and YAML which is a data serialization format used for configuration files. For this blog post, we’ll use TypeScript. Pulumi enables automation of the deployment process, leading to faster and more reliable infrastructure provisioning. The Pulumi provider we use is based on the official Terraform Provider from Confluent Inc., ensuring broad compatibility across various languages and platforms. Although we’re focusing on Confluent Cloud here, Pulumi’s capabilities are versatile, allowing you to apply similar processes to other cloud platforms like AWS, Azure, GCP, Digital Ocean, and Aiven, as well as indirectly managing on-premise workloads through Kubernetes. Essentially, Pulumi’s on-premise management capabilities are achieved through Kubernetes rather than direct interaction with on-premise infrastructure. Provisioning Kafka Topics To provision Kafka topics with Pulumi, follow these steps: Define Cluster Arguments: Specify the Kafka cluster where the topics will be provisioned. \ 1 2 3 let clusterArgs: KafkaTopicKafkaCluster = { id: cluster_id, }; Set Kafka Credentials: Provide the API key and secret for authentication. \ 1 2 3 4 let clusterCredentials: KafkaTopicCredentials = { key: kafka_api_key, secret: kafka_api_secret, }; Configure Topics: Define the configurations for your Kafka topics, such as retention policies and partition count. 1 2 3 4 5 6 7 8 9 10 11 let topic_args: KafkaTopicArgs = { kafkaCluster: clusterArgs, topicName: topicName.toLowerCase(), restEndpoint: rest_endpoint, credentials: clusterCredentials, config: { ["retention.ms"]: "-1", ["retention.bytes"]: "-1", ["num.partitions"]: "6", }, }; Create Topics: Instantiate and create the Kafka topics. \ 1 2 3 4 const topics = new confluent.KafkaTopic( topicNames[i].toLowerCase(), topic_args ); Run Pulumi: Save your code to index.ts, set the Confluent Cloud credentials, and run the following commands: 1 2 3 pulumi config set confluentcloud:cloudApiKey --secret pulumi config set confluentcloud:cloudApiSecret --secret pulumi up Terraform for Infrastructure as Code Terraform is a popular IaC tool that supports a wide range of cloud, datacenter, and service providers, including Azure, AWS, Oracle, Google Cloud, Digital Ocean, Redpanda, Aiven, and Kubernetes. It uses HashiCorp Configuration Language (HCL) to describe and provision infrastructure. Provisioning Kafka cluster and topics with Terraform To provision Kafka clusters and topics using Terraform, follow these steps to set up your infrastructure in Confluent Cloud. Initialize the Provider Start by specifying the Confluent provider in your Terraform configuration: 1 2 3 4 5 6 7 8 terraform { required_providers { confluent = { source = "confluentinc/confluent" version = "1.13.0" } } } This installs the Confluent Cloud provider. Configure Confluent Secrets Set up your Confluent credentials by adding the following to your Terraform configuration. Note that sensitive information, such as API keys and secrets, should be handled securely. These credentials should not be stored directly in your version control system. Instead, consider using a secret management tool or environment variables to manage sensitive information securely. Set up your Confluent credentials: 1 2 3 4 provider "confluent" { cloud_api_key = var.confluent_cloud_api_key # Optionally, use CONFLUENT_CLOUD_API_KEY env var cloud_api_secret = var.confluent_cloud_api_secret # Optionally, use CONFLUENT_CLOUD_API_SECRET env var } Create a Kafka Cluster Define the Kafka cluster where the topics will be provisioned. This cluster will be created in Confluent Cloud: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 resource "confluent_kafka_cluster" "basic" { display_name = "basic_kafka_cluster" availability = "SINGLE_ZONE" cloud = "AWS" region = "us-east-2" basic {} environment { id = var.environment_id } lifecycle { prevent_destroy = true } } Define Kafka Topics Configure the Kafka topics in your Terraform configuration file: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 resource "confluent_kafka_topic" "dev_topics" { kafka_cluster { id = var.cluster_id } for_each = toset(var.topics) topic_name = each.value rest_endpoint = data.confluent_kafka_cluster.dev_cluster.rest_endpoint partitions_count = 6 config = { "retention.ms" = "604800000" } credentials { key = var.api_key secret = var.api_secret } } Run Terraform Commands To create and manage the infrastructure: Initialize Terraform: This command installs the necessary providers and prepares your Terraform working directory. 1 terraform init Apply Terraform Configuration: This command provisions the Kafka cluster and topics as specified in your Terraform configuration. It creates the infrastructure in Confluent Cloud based on the configurations provided. 1 terraform apply Features of IaC Tools: JulieOps, Terraform, and Pulumi Conclusion Choosing the right Infrastructure as Code (IaC) tool depends on your specific needs. Terraform is known for its stability and extensive resource support, making it a reliable choice for many. Pulumi offers ease of use and supports multiple programming languages, appealing to those with coding experience. JulieOps focuses on managing Kafka resources within Cloud. Each tool has its unique strengths, offering effective solutions for managing infrastructure code. --- # Real-time Data on Prime-Time URL: https://platformatory.io/blog/real-time-data-prime-time/ Published: 2024-08-01 Authors: Pavan Keshavamurthy Categories: Real-time, Stream Processing, Kafka, Platform Engineering The speed of light in vacuum, according to general relativity, is 3 * 10^8 m/s. All things fundamentally real-time are bound by the existing laws of physics (unless you consider hypothetical superluminal particles). This includes computing as well. CPU clock speeds, flipping bits in memory, writing to and reading from storage, and transferring bytes over a network all take time. So what does it mean to build “real-time” architectures within this reality? On one hand, you have hard real-time operating systems that must provide “hard” real-time guarantees, preemption and deterministic behavior in extremely low latency bounds. These rely on hardware interrupts. For everything else, we rely on the kernel scheduler. For our purposes: real-time data basically refers to architectures that rely on data freshness, of the order of milliseconds to a few seconds of latency, at the inner loop of some process. While this metaphor is prevalent in many industries, such as for example Industrial IoT, where it is crucial to detect imminent system failures that can cascade in the order of a few seconds, it is also present prominently in various touch points of customer experience in the “human plane”, such as a being able to prevent fraud or provide a real-time, hyper local offer. As the rate of data generated explodes YoY at a rate of 25% (from a whooping 120 ZB in 2024), being able to contextualize and react to data/events in (near) real-time becomes a crucial capability. To achieve this requires a holistic architecture vision and a number of fit-to-purpose platform components. Napkin Math Numbers (2024) Before we dive deep into the minutiae of how to build real-time data architectures, let’s do some napkin math: To read/write a 1GiB to sequential memory, at a throughput of 10 GiB/s, using a single thread and no SIMD takes approximately 100ms. With SIMD, you could do it up to 4 times faster. To read 1GiB sequentially from an SSD, you will need 200ms. To write the same data (without fsync) it will take 1s. To write the same data with fsync, it will take 2 minutes. A random read would take 15 seconds on average. Network within the same AZ would have a ping latency of 0.25 ms. Adjacent inter-region would be in the order of 10 - 40ms. Between different regions of the cloud provider (“backbone”), this could increase up to 180ms. An object storage operation would be 50ms. S3-Express-1Z would be 10ms. These are theoretical numbers on standard hardware. Real-life workloads are usually slower than their published benchmarks due to unique characteristics. Data workloads vary significantly based on the use-cases they target. Almost nothing of scale fits into a single machine anymore, so a distributed workload with a networking element adds more complexity. Operational data comprises classically OLTP datastores, where the access pattern largely results in row-based storage formats working better. Analytical data comprises, on the other hand, OLAP databases which layout the data along columns. This distinction is important for technical reasons and has implications for how enterprises manage these data estates. This dichotomy also has implications of Conway’s law in that the teams (and org structures) that manage these data estates are different, sometimes with opposing forces and domains of control. However, to provide the real-time experience the latence ping-pong between these data estates must still be bounded within the subsecond to few seconds range. Typical Enterprise Data Flow In order to unpack what makes this complex, let’s consider a classic enterprise data saga: flowchart TB user[User] -->|Interacts with| requestService[Request-Response Service] requestService -->|Saves Data| db[(Oracle/Postgres)] db -->|Broadcasts Events| kafka[(Apache Kafka)] db -->|Triggered by| scheduledJob[Scheduled Job] kafka -->|Ingests Batches| s3[(AWS S3)] scheduledJob -->|Ingests Batches| s3 s3 -->|Cleanses and Transforms Data| etlService[Cleansing & Transformation Service] etlService -->|Stores Transformed Data| snowflake[(Snowflake)] snowflake -->|Provides Data| dashboard[Power BI Dashboard] dashboard -->|Views Reports| ceo[CEO] This outlines a “conventional” batch-oriented data architecture, which fundamentally acts upon data stored at rest. However, they generally follow “reload and recompute” everything semantics and therefore large latency penalties to access the storage layer, then load everything into memory, process the results and write it back. This begs the question: Why isn’t incremental processing on data as it arrives the right thing to do? The answer is, yes (but is it worth it?). It comes with a lot of nuances that arise out of different notions of time domain processing, consistency models (“processing semantics”) and expectations on completeness & correctness. Combined with all fallacies of distributed computing, and the fact that we are acting upon unbounded data and finite computing resources. We have to process decisions based on a snapshot of “what we know now,” knowing that we may not have the full information. Since we’re throwing physics metaphors in the post: Batch vs Streaming is a little like classical mechanics and quantum mechanics. Bottom line: Optimizing for latency is hard. Real-time is hard. Think about a traffic flow analogy. It is easier to design a city with traffic lights than without. However, you need different principles to manage air traffic. Components for a Lower Latency, Real-time Stack Based on everything we know in 2024, let’s explore the emerging real-time platform stack and analyze them from a standpoint of characteristic latency profiles. When we talk through latency numbers here, we almost always refer to “ballpark” numbers on real-life workloads profiles. We will also specially qualify “end-to-end” latency, which is a summation measure across multiple legs of a single logical pipeline of data, across the operational <-> analytics divide. We also assume non-specialized workloads: i.e., moderate throughputs, high availability, strong needs for consistency and correctness, and ordinary infrastructure you can afford on the cloud. Tail latency is the most important consideration, so you can generally assume we are referring to p99 out here both for reads and writes. Based on this, we can identify at least 7 crucial classes of components you would typically require to build a fit-to-purpose architecture for real-time use-cases (1) Real-time Databases Conventional databases like PostgreSQL, Oracle, and MySQL adhere to the ACID (Atomicity, Consistency, Isolation, Durability) principles to ensure reliable transaction processing. These databases guarantee that all operations within a transaction are completed successfully or none are, maintaining data integrity even in the case of failures. They achieve this through mechanisms such as Write-Ahead Logging (WAL), where changes are first written to a log before being applied to the database. This ensures that data can be recovered in the event of a crash. Additionally, fsync operations ensure that data is flushed from volatile memory to persistent storage, preventing data loss. However, these processes introduce latency due to the multiple write operations and the need to achieve consensus among replicas (quorum writes). As a result, while they provide strong guarantees of data consistency and reliability, they are relatively slower compared to newer database technologies. Databases like Aerospike, which are optimized for high performance, also provide immediate consistency. Aerospike uses a hybrid memory architecture where indexes are stored in DRAM while data is written directly to flash storage. It uses a form of Write-Ahead Logging to ensure durability, but optimizes the process to minimize latency. Aerospike’s design allows it to achieve low read and write latencies while maintaining strong consistency guarantees. The use of in-memory processing for indexes and optimized data paths for flash storage enables high throughput and efficient handling of large volumes of data. In-memory databases like Redis, Memcached, and SAP HANA store data entirely in RAM, providing extremely fast read and write operations. By eliminating the need for disk I/O, these databases can achieve sub-millisecond latencies. Redis, for instance, maintains data structures like strings, hashes, lists, sets, and sorted sets in memory, allowing for quick data access. In-memory databases are particularly useful for applications that require real-time analytics, caching, or session management. However, the reliance on RAM makes them more expensive and less durable than disk-based databases. To mitigate this, many in-memory databases offer persistence options such as snapshotting and append-only files, which periodically write data to disk to prevent data loss in case of a system failure. sequenceDiagram participant Client participant DB as Database participant WAL as Write-Ahead Log participant Disk as Disk Storage participant Replica as Quorum Write Client->>DB: Write Request DB->>WAL: Write to WAL WAL->>DB: Acknowledgement DB->>Disk: Write to Disk Disk->>DB: Acknowledgement opt Strong Consistency DB->>Replica: Quorum Write Replica->>DB: Acknowledgement end DB->>Client: Write Acknowledgement Client->>DB: Read Request DB->>Disk: Read Data Disk->>DB: Data Response DB->>Client: Read Response Real-time databases are beautiful. They are amazing feats of computing that enable truly real-time classes of experiences that power thing like matching users to ads, players in real-time gaming and even stock market bids. However, with real-time (and the regular databases), it is inevitable that data must at some point be copied over to the analytical estate. The lowest latency way to do it is through a database write-aside approach. graph LR A[Client] -->|Write Request| B[Database] B -->|Write to Outbox| C[Outbox Table] C -->|Commit Transaction| D[Database] D -->|Publish| E[Kafka] E --> F[Downstream Systems] TL/DR Most SQL databases will come at high double digit latencies The most performant modern NoSQL stores can deliver low single digit millis latencies. Best representatives of real-time OLTPs would be: Aerospike DB, ScyllaDB, Apache Ignite, DynamoDB In-memory databases provide sub millisecond latencies consistently (but poor durability). Embeddable in-process databases like RocksDB spill to disk (therefore durable at only marginal latency cost) but require users to implement many features themselves You must think about how to transmit changes to real-time. Ideally, a dual-write to a system like Kafka, within the database transaction boundary OR through approaches like CDC (2) Streaming Pipes and Connectors We mentioned inevitably gets copied and moved around a lot. While the write-aside approach works, often it is infeasible due to organizational constraints and architecture deficit. This almost always necessitates the need for a connector layer to move data around from one system to another. While this can be done through point to point copies, it is unreasonably effective to plug in a large persistent buffer like Kafka that optimizes for low latency, high throughput ingestion (even for very bursty workloads) and high fan-out. This also means that connector architectures that rely on top of Kafka have a lot of advantages, such as being able to fence data movement into transactions, retry and generally insulate against unavailability of systems that are in the pipeline. Write-Through (CDC using WAL) Approach: graph LR A[Client] -->|Write Request| B[Database] B -->|WAL| C[Write-Ahead Log] C -->|Change Detected| D[CDC Process] D -->|Publish| E[Kafka] E --> F[Downstream Systems] Connectors are responsible for moving data between different systems or components within a distributed architecture. They play a crucial role in ensuring that data flows seamlessly from sources to sinks. The performance of connectors is influenced by several factors including source-side latency, sink-side processing latency, transformation latency, and sink put latency. Source-side latency is dependent on the poll frequency and network conditions. It measures the time it takes to capture data from the source system. For example, a connector might poll a database or a message queue at regular intervals to fetch new data. Network conditions can affect this latency, especially if the source and the connector are located in different regions. Sink-side processing latency, also known as consumer lag, measures the time it takes for the data to be processed by the sink system after it has been captured by the connector. This can vary based on the load on the sink system and its capacity to process incoming data. Transformation latency refers to the time taken to transform or process data as it moves through the connector. This can occur on both the source side and the sink side. Transformations might include data enrichment, filtering, or format conversion. While transformations add flexibility and value to the data pipeline, they also introduce additional latency. Sink put latency measures the time it takes to write the transformed data into the sink system. This latency depends on the performance of the sink system, the network conditions, and the volume of data being written. graph LR A[Source] -->|Poll| B[SourceTask] B -->|Optional Transform| C[Kafka] C -->|Consume| D[SinkTask] D -->|Optional Transform| E[Sink] TL/DR Kafka tail latencies are of the order of single digit milliseconds. Typical connector pipelines can have anywhere between a few seconds to many minutes of end to end latency. Increasing parallelism usually helps improves latency This lag is by design and can withstand bursty workloads and unavailable systems CDC connectors usually operate with a single thread sourcing a totally ordered WAL. They are prone to larger lag (on high throughput databases) and snapshotting times to backfill existing data. Usually push approaches work better if low latency is a concern (3) Stream Processing Stream processing involves continuously processing data streams in real-time. This typically includes a source processor that reads data from a source Kafka, multiple transformation or other operators (including UDFs) with state stores, and a sink processor that writes processed data back to a sink that supports acknowledgements like Kafka. Each component in this pipeline can introduce latency, and understanding these factors is crucial for optimizing performance. Operators apply various operations such as filtering, enrichment, aggregation, and joins. These operators can be stateless or stateful. Stateless operations generally incur lower latency as they do not need to maintain any state between records. Stateful operations, however, need to maintain and update a state store, which introduces additional latency. The state store operations involve reading and writing state data, and depending on the implementation, can significantly impact performance. The sink processor writes the processed data back to Kafka. The latency in this step depends on the performance of the Kafka cluster and the network conditions. A queryable state layer allows applications to query the state stores directly. This layer provides real-time access to the state maintained by the stream processing application, enabling low-latency queries on the processed data. However, this additional layer usually needs to be backed up by a scalable API layer and metadata augmentation to locate the state store by the key. sequenceDiagram participant Kafka as Kafka participant SourceProcessor as Source Processor participant Operators as Operators participant SinkProcessor as Sink Processor Kafka->>SourceProcessor: Read Data SourceProcessor->>Operators: Process Data Operators->>SinkProcessor: Write Data SinkProcessor->>Kafka: Commit graph TD A[Kafka Source] --> B[KeyBy Function] subgraph Parallel Processing B --> C1[Map Function 1] B --> C2[Map Function 2] B --> C3[Map Function 3] C1 --> D1[Filter Function 1] C2 --> D2[Filter Function 2] C3 --> D3[Filter Function 3] end subgraph State Stores D1 --> E1[State Store 1] D2 --> E2[State Store 2] D3 --> E3[State Store 3] end E1 --> F[Sink Processor] E2 --> F E3 --> F F --> G[Kafka Sink] Streaming databases and stream processing systems do very similar things. One would be inclined to think that streaming databases as syntactic sugar on top of stream processing systems, however this would be very inaccurate. Streaming databases are much more akin to databases, take on state (and persistence) as a first class concern, while completely insulating users from low level APIs used for managing dataflow. For instance, the Timely Dataflow Model, based on NAIAD, emphasizes the coordination of data processing across distributed systems. It introduces the concept of epochs and progress tracking, enabling efficient and scalable data processing. The timely dataflow model supports both cyclic and acyclic data flows, making it versatile for various streaming applications. This is starkly in contrast to DAG based topologies common in stream processing systems. Streaming databases have very solid fundamentals and could easily become relevant for 80% of stream processing use-cases without the complexity of large systems like Flink, Spark (or even libraries like KStreams for that matter). TL/DR Stream processing pipelines are based on Read-Process-Write loops through parallel topologies. On an average, they may add between several milliseconds to seconds of latency (or more) depending on the size & shape of the topology, whether they handle stateful operations, the choice of state backend, window length and other considerations. Further, they also have to rely on concepts like watermarks and grace periods to adhere to expectations of completeness and correctness. Shuffles, Checkpointing (if/where supported), Effectively once semantics can all have a significant impact on throughput Streaming databases generally undertake storage as a first class concern and have state store bound latency that is higher than local state stores used by stream processing frameworks (4) Real-time OLAP Real-time Online Analytical Processing (OLAP) systems like Apache Druid, Apache Pinot, and ClickHouse are designed to provide low-latency queries on large volumes of streaming and historical data. These systems are optimized for analytical queries that require fast aggregations, filtering, and complex calculations. They typically ingest data from streaming sources, index and store the data in an efficient (columnar) format, and provide a query interface that allows for high concurrency and fast response times. Indexed data is stored in deep storage systems such as HDFS, S3, or local disks. The storage layer ensures data durability and availability for historical queries. Query nodes, or brokers, handle incoming queries by distributing them across multiple data nodes. These nodes perform a scatter-gather operation, where subqueries are executed in parallel, and the results are aggregated and returned to the user. Real-time OLAP systems are designed to handle high query concurrency, horizontal scale-out, ensuring that multiple users can run complex queries simultaneously without significant performance degradation. graph TD A[Client] --> B[Query Nodes] B -->|Scatter| C1[Data Node 1] B -->|Scatter| C2[Data Node 2] B -->|Scatter| C3[Data Node N] C1 --> D[Deep Storage] C2 --> D[Deep Storage] C3 --> D[Deep Storage] D --> E[Indexing Service] E --> F[Ingestion Service] F --> G[Streaming Source] C1 -->|Gather| B C2 -->|Gather| B C3 -->|Gather| B B --> A TL/DR: Real-time OLAP systems are the proverbial materialization layer for “large amounts of streaming data with sub-second query SLAs” - especially for systems such as ad-serving, real-time analytics with large scale concurrency For RTOLAP systems to be real-time, it is imperative to maintain tight control on ingestion. Pull-based ingestion with low level consumer optimizations (as opposed to consumer groups) yield lower ingestion latencies Indexes a major role on the query latency. However, a number of table engine nuances (such as support for upserts or the lack thereof), compaction etc need to be managed well, along with optimal sizing of segment sizes on the query nodes, query optimizations, generally avoiding joins by denormalizing tables and strongly considering pre-aggregations and roll-ups on ingest (5) The Data Lakehouse Distributed file systems have been at the backbone of every large scale data architecture over the years. The cloud native era has seen S3 emergency at the core of nearly every data system that desires compute and storage decoupling, including lakes, warehouses, a streaming API like Kafka itself and even transactional databases. The recent years have seen the coalescence of lakes and warehouses, mainly owing to two important factors, namely the commodification of: Open table formats on top of columnar storage formats Query Engines: Robust vectorized query execution, predicate pushdowns, etc While that has been the case, their utility in mainstream “streaming” applications has been relatively low because of prohibitively high latencies on the storage layer (which generally prefers larger files than smaller files) and some structural reasons of the table format themselves. For example, Apache Iceberg, the leading open table formats has major deficiencies with streaming workloads. However, this is fast changing due to a couple of factors The emergence of next-gen formats, such as Apache Hudi and Apache Paimon. Hudi’s Merge on read (MOR) tables are very efficient for streaming ingestion, supports CDC connectors natively, along with schema evolution and deep integrations with processing system. Apache Paimon, which is Flink’s table format, provides some very efficient LSM reuse optimisations and deep integrations with Flink itself makes lakehouse architectures reach closer to the latencies desired, but at much cheaper costs Object stores are themselves getting faster (and will keep getting faster). This means there may be times in the future where they may just become viable for a new world order of data architectures. graph TD A[Client] --> B[Query Engine] B -->|Query| C[Metadata Layer] B -->|Vectorized Execution| D[Open Table Format] D --> E[Object Storage] E --> D D -->|Data Retrieval| B C -->|Index Lookup| D C -->|Schema Evolution| D It is inevitable that any architecture that could benefit from compute-storage separation, geo-resilience and cost optimization will build on top of object stores like S3. TL/DR Lakehouses can easily provide a unified processing and storage layer for most moderate to high latency workloads that need a streaming foundation: Particularly use-cases such as CDC When done well, streaming lakehouses can fill the large void between RTOLAP and traditional lakes and warehouses. It is viable to achieve near-time streaming pipelines with an end to end latency of several seconds to several minutes Not all table formats are equal. While the incumbent table formats largely lean towards traditional batch workloads, some emerging ones provide a solid foundation for streaming As cloud object storage gets faster (ex: S3 Express 1Z), viability of lakehouses for streaming workloads will only get better (6) Real-time ML (and datastore bolt-ons) For a burgeoning data estate with these 5 essentials started out, the more futuristic possibilities of leveraging real-time data are in the AI/ML (including Gen AI space). This necessitates the application of both generic and specialized data stores. For example, time series databases excel at aggregation of data at extremely low latencies on high volume time-series data. Feature stores are emerging as a system of record for managing ML features and reference data, for both online and offline serving as an integrated concern (with low latency). Interest in vector databases, a class of databases that mainly excel at large scale similarity searches, has seen a huge surge mainly due to the advent of GenAI approaches such as RAG, which require context hydration to the LLM at inference time. While these parts of the stack have been assembled bespoke in the ML niche often on single purpose products, there is a clear potential for unifying and standardizing various parts of the ML platform and Operations stack. The primary concern being, optimizing for inference latency, with models augmented by the freshest data that is available. The final frontier is to enable smarter model operations with continual and incremental learning (a function of both retraining and fine-tuning frequency), while being able to put in controls on evaluation and taming model drift. TL/DR Latency Profile: Online feature stores optimize for latencies profiles of the order of milliseconds for serving up real-time features in the path of inference. This usually means that the feature store uses something akin to a Redis, Aerospike or Cassandra. This also needs to be coupled with a robust model serving / API layer and caching. Vector stores also fall in the same range, but latencies usually fluctuate as a function of the distance metric and the number of vector dimensions. LLM chains and RAG pipelines must consider vector databases in the path as the additional overhead that needs to be optimized. Continual learning is still an area of novelty, coupled with many challenges of explainability and model evaluation, but will emerge as an area, likely building on top of abstractions like Conclusion Optimizing for latency is hard. Ubiquitous firehose interfaces like Kafka form the lowest common denominator of the distribution and in-motion logistics needed to build real-time experiences that span across the operational, analytical divide. However, these need to be combined with a best in breed stack to process, materialize, query and manage the streaming estate. --- # Learning by Debugging: Kafka Local Setup URL: https://platformatory.io/blog/Learning-by-Debugging-Kafka-Local-Setup/ Published: 2024-07-31 Authors: Subramanya Madhyastha Categories: Kafka, Local Development, Troubleshooting Introduction: In the realm of data streaming and event-driven architectures, hands-on experience and real-time troubleshooting is invaluable. This blog aims to provide an in-depth guide to setting up and using a local Kafka environment using Docker-compose, by leveraging a sandbox setup, you can experiment, test, and debug Kafka configurations in an isolated environment that mimics a cloud setup, why use an environment that mimics a cloud setup you ask? We have a blog on the exact thing and it explains why having a local kafka setup is very essential. Make sure to check it out too Unlocking the Potential of Local Kafka. A sandbox is an isolated environment that allows developers to safely test and troubleshoot without impacting the production environment. This makes it an essential tool for ensuring that code changes and configurations work correctly before deployment. In this blog, we will introduce the Confluent Platform Sandbox and Confluent Platform Ansible Sandbox, powerful tools that simplify the process of setting up and managing Kafka clusters locally using Docker Compose. We will guide you through the step-by-step process of setting up the CP Sandbox, show how it can be used for testing and debugging, and delve into various troubleshooting scenarios. Additionally, we will cover the integration of monitoring tools like Prometheus and Grafana for enhanced observability and debugging. Finally, we will introduce the CP Ansible Sandbox, which automates the deployment and management of Kafka clusters, further streamlining your development workflow. The CP Sandbox- Usage and Setup: The CP Sandbox is built using Docker Compose, which allows us to define and run multi-container Docker applications seamlessly. This setup includes a comprehensive environment with Confluent Kafka and its essential components, making it ideal for simulating a production-like setup on local machines. Here’s a detailed look into its setup and components: Configuration Mounting: The Docker Compose file mounts configuration files (properties files) into the containers. These properties files are critical as they allow customization of each component’s settings, ensuring the environment behaves just like it would on VMs or bare-metal servers to a certain extent. Simulating Production Environments The environment simulates running Confluent Platform on VMs or bare-metal servers but leverages Docker containers for convenience and portability. This simulation is achieved by: Properties Files: Using properties files to configure Kafka and its components, mirroring how configurations would be managed in a non-containerized setup. This approach ensures that the transition from development to production is smooth, as the configurations remain consistent. Docker Containers: Docker containers encapsulate each service, providing isolation and consistency. This means you can run the same environment on any machine with Docker installed, ensuring that your setup behaves predictably across different development and testing environments. Troubleshooting Scenarios The CP Sandbox repository includes various branches, each containing different troubleshooting scenarios. These scenarios are designed for Kafka administrators to practice handling production-like issues. Some examples include: Topic Access Issues: Simulate the inability to produce or consume from a newly created topic. This helps administrators practice checking and configuring ACLs, verifying user permissions, and ensuring network connectivity. Missing Broker Metrics: Address issues where broker metrics are not captured in the control center despite setting up Confluent Metrics Reporter. This scenario helps in verifying configuration settings and connectivity between brokers and the control center. Platform Migration Issues: Simulate issues following a lift-and-shift migration to different machines, such as SSL handshake failures or configuration mismatches. Administrators can practice resolving these problems by examining error logs and reconfiguring components. These scenarios provide hands-on experience in diagnosing and resolving issues, making administrators better prepared for real-world challenges. Here is a step by step guide on setting up the CP Sandbox: Clone the Repository: Start by cloning the repository containing the Docker Compose file and configuration files, you can access the repository via this link. 1 git clone git@github.com:Platformatory/cp-sandbox.git 1 cd cp-sandbox Start the Services: Use Docker Compose to start all the services defined in the docker-compose.yml file. 1 docker-compose up -d This command will bring up a three-node Kafka cluster with security enabled, along with other components like Zookeeper, Schema Registry, Kafka Connect, Control Center, Prometheus, Grafana, and OpenLDAP. NOTE: Be sure to update or extend the validity of the SSL certificates for the Kafka brokers. Expired certificates can cause broker containers to go down due to authentication errors resulting from invalid certificates. Use the blog post here for a guide on how to renew an expired SSL certificate. Use the below command to inspect the keystore and check the validity of the certificate. 1 keytool -list -v -keystore <> (The keystore file, kafka.server.keystore.jks is located in the broker folder for each broker) Check Service Status: Verify that all services are up and running. 1 docker-compose ps -a Ensure there are no exited services and all containers have the status Up. If any of the containers have gone down, examine the logs of the respective containers as shown below to get a better understanding of the issue for troubleshooting. Logging: Check the logs of the respective service by its container name. 1 docker logs <> Monitoring: For monitoring, Prometheus and Grafana are configured to visualize JMX metrics. Using the Kafka Client: To interact with the Kafka cluster, you can use the Kafka client container. 1 docker exec -it kfkclient bash The Kafka client container contains the Kafka CLI and other tools necessary for troubleshooting Kafka. It also includes a properties file mounted to /opt/client that can be used to define client properties for communicating with Kafka. Restarting Services: If needed, you can restart a particular service. 1 docker-compose restart <> Alternatively, you can force recreate the service. 1 docker-compose up -d --force-recreate <> Below is a part of the docker-compose file from the repository which sets up the Confluent Kafka and Zookeeper resources with JMX metrics exposed, using Docker containers. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 --- version: '3.7' services: zookeeper1: image: confluentinc/cp-zookeeper:7.4.0 hostname: zookeeper1 container_name: zookeeper1 ports: - "2181:2181" command: zookeeper-server-start /etc/kafka/zookeeper.properties environment: EXTRA_ARGS: -javaagent:/usr/share/jmx-exporter/jmx_prometheus_javaagent-0.20.0.jar=9103:/usr/share/jmx-exporter/zookeeper.yml volumes: - ./zookeeper1:/etc/kafka - ./jmx-exporter:/usr/share/jmx-exporter deploy: resources: limits: cpus: "1" memory: 512M kafka1: image: confluentinc/cp-server:7.4.0 hostname: kafka1 container_name: kafka1 depends_on: - zookeeper1 command: kafka-server-start /etc/kafka/server.properties environment: EXTRA_ARGS: -javaagent:/usr/share/jmx-exporter/jmx_prometheus_javaagent-0.20.0.jar=9101:/usr/share/jmx-exporter/kafka_broker.yml volumes: - ./kafka1:/etc/kafka - ./jmx-exporter:/usr/share/jmx-exporter deploy: resources: limits: cpus: "1.5" memory: 1536M The current setup uses Confluent Platform version 7.4.0 as specified by the image confluentinc/cp-server:7.4.0 in the above code, this version is compatible with the 3.4 version of Apache Kafka (Refer here for Supported Versions and Interoperability for Confluent Platform) Visit the Confluent Docker Hub to find the latest version of the Confluent Kafka images and use the image for upgrading to the latest version. Troubleshooting using the Platformatory Kafka Sandbox: The sandbox includes 12 distinct troubleshooting scenarios, selected from key Kafka concepts and potential production issues. Each scenario is available on a different branch of the repository, allowing you to switch between branches to practice and resolve various Kafka-related challenges. Below are a few scenarios from the repository: Scenario 1 Problem Statement The client has created a new topic europe_payments but is unable to produce/consume from the topic from the host kfkclient using the user kafkaclient1 using the following commands - 1 kafka-console-producer --bootstrap-server kafka1:19092 --producer.config /opt/client/client.properties --topic europe_payments 1 kafka-console-consumer --bootstrap-server kafka1:19092 --consumer.config /opt/client/client.properties --from-beginning --topic europe_payments The client is using SASL/PLAIN over PLAINTEXT with the user kafkaclient1 The error message seen in the console producer and consumer for europe_payments - 1 2 3 4 5 6 7 [2023-07-26 12:18:20,309] WARN [Producer clientId=console-producer] Error while fetching metadata with correlation id 4 : {europe_payments=TOPIC_AUTHORIZATION_FAILED} (org.apache.kafka.clients.NetworkClient) [2023-07-26 12:18:20,409] ERROR [Producer clientId=console-producer] Topic authorization failed for topics [europe_payments] (org.apache.kafka.clients.Metadata) [2023-07-26 12:18:20,411] ERROR Error when sending message to topic europe_payments with key: null, value: 6 bytes with error: (org.apache.kafka.clients.producer.internals.ErrorLoggingCallback) org.apache.kafka.common.errors.TopicAuthorizationException: Not authorized to access topics: [europe_payments] Scenario 2: Problem Statement There are no broker metrics captured in the control center. The control center has a message - Please set up Confluent Metrics Reporter to view broker metrics. The customer has setup Confluent Metrics Reporter but is still unable to view broker metrics Scenario 3 Problem Statement The client just performed a lift and shift on their entire platform to different machines. The brokers and several other components are down. The brokers have the following error log - 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 java.lang.RuntimeException: Received a fatal error while waiting for all of the authorizer futures to be completed. at kafka.server.KafkaServer.startup(KafkaServer.scala:950) at kafka.Kafka$.main(Kafka.scala:114) at kafka.Kafka.main(Kafka.scala) Caused by: java.util.concurrent.CompletionException: org.apache.kafka.common.errors.SslAuthenticationException: SSL handshake failed at java.base/java.util.concurrent.CompletableFuture.encodeRelay(CompletableFuture.java:367) at java.base/java.util.concurrent.CompletableFuture.completeRelay(CompletableFuture.java:376) at java.base/java.util.concurrent.CompletableFuture$AnyOf.tryFire(CompletableFuture.java:1663) at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:506) at java.base/java.util.concurrent.CompletableFuture.completeExceptionally(CompletableFuture.java:2088) at io.confluent.security.auth.provider.ConfluentProvider.lambda$null$10(ConfluentProvider.java:543) at java.base/java.util.concurrent.CompletableFuture.uniExceptionally(CompletableFuture.java:986) at java.base/java.util.concurrent.CompletableFuture$UniExceptionally.tryFire(CompletableFuture.java:970) at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:506) at java.base/java.util.concurrent.CompletableFuture.completeExceptionally(CompletableFuture.java:2088) at io.confluent.security.store.kafka.clients.KafkaReader.lambda$start$1(KafkaReader.java:102) at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515) at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at java.base/java.lang.Thread.run(Thread.java:829) Each of the scenarios are presented in a similar way with a problem statement, detailing the issue the user is encountering, the commands attempted while facing the issue, and the error message received that can be used for troubleshooting the issue. Monitoring and Metrics: Each Kafka and Zookeeper instance is configured with a JMX exporter, which exposes metrics in a format that Prometheus can scrape, prometheus scrapes these metrics from the JMX exporters at regular intervals. Grafana queries Prometheus for the stored metrics and presents them in various visual formats, such as graphs, charts, and tables. 1 EXTRA_ARGS: -javaagent:/usr/share/jmx-exporter/jmx_prometheus_javaagent-0.20.0.jar=9101:/usr/share/jmx-exporter/kafka_broker.yml In the above code snippet taken from the Docker Compose configuration, the EXTRA_ARGS environment variable is used to enable JMX (Java Management Extensions) monitoring by specifying a Java agent. This agent collects metrics and exposes them in a format that can be scrapped by Prometheus. Accessing the Grafana Dashboard: Open your browser and go to http://localhost:3000. The default login credentials are admin for both the username and password. You can change these after the first login for security purposes. Explore Dashboards: Once logged in, navigate to the pre-configured dashboards to start monitoring the Kafka cluster. You can create additional dashboards and visualizations as needed. Below are a couple of snapshots from the Kafka Cluster Dashboard. This dashboard houses some of the key metrics for the Cluster monitoring such as Basic Broker Metrics, Request Rate Metrics and System Metrics such as CPU Usage and JVM Memory Usage. Another resource we use here at Platformatory is CP-Ansible Sandbox, This sandbox provides an automated way to set up and manage Kafka environments using Ansible playbooks, making the deployment process fully automated. Introduction to the CP-Ansible Sandbox The CP-Ansible sandbox can be used for automated deployment and management of Confluent Platform clusters. This sandbox environment allows us to simulate and manage our Kafka infrastructure efficiently using Ansible playbooks within a Dockerized setup. This provides a seamless and consistent environment for testing, deploying, and managing Kafka clusters. The CP-Ansible sandbox is designed to run within a Docker environment. It includes a control node container and multiple inventory nodes, all managed through systemd and SSH. This setup enables us to execute Ansible playbooks to manage the Kafka clusters from a central control node. The Cluster contains the following resources deployed: Ansible Control Node 3 Zookeeper 3 Kafka Brokers Control Center Setting Up the CP-Ansible Sandbox Cloning the Repository: Start by cloning the repository, you can access the repository via the link. 1 Git clone git@github.com:Platformatory/cp-ansible-sandbox.git 1 git submodule update --init --recursive Starting the Docker Environment: 1 docker compose up -d Verifying Containers: 1 docker compose ps -a Setting Up SSH Keys: 1 ./setup-ssh-keys.sh Accessing the Ansible Control Node: 1 docker compose exec -it ansible-control bash Once the environment is set up, the control node can manage all inventory nodes via SSH. The Ansible playbooks can be executed from this control node to deploy and manage the Confluent Platform. Verifying SSH Connectivity Inside the Ansible control node, verify the SSH connectivity with other nodes: 1 ssh root@zookeeper1 Running the CP-Ansible Playbook Install the Confluent Platform playbook: Run the below command inside the Ansible Control Node Container 1 ansible-playbook confluent.platform.all This assumes the inventory file is located at /ansible/inventories/ansible-inventory.yml. Below is the inventory script for setting up the cluster. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 --- all: vars: ansible_connection: ssh ansible_user: root ansible_become: true ansible_ssh_private_key_file: zookeeper: hosts: zookeeper1: zookeeper2: zookeeper3: kafka_broker: hosts: kafka1: kafka2: kafka3: control_center: hosts: control-center: Custom Inventory Files To use a custom inventory file: 1 ansible-playbook -i /path/to/custom/inventory-file confluent.platform.all Managing the Inventory The inventory files are located in the inventories directory and are mounted to /ansible/inventories/ on the control node container. You can create new inventory files or update existing ones locally, and these changes will be reflected on the control node. Additional Files Any additional files needed for the Ansible playbooks can be added to the share directory locally. These files will be available in /usr/share/cp-ansible-sandbox on the Ansible control node. Conclusion By using the CP Sandbox and CP-Ansible Sandbox, developers and administrators can effectively set up, manage, and troubleshoot Kafka clusters in a controlled, isolated environment. These sandboxes offer a hands-on approach to learning, testing, and debugging Kafka configurations, mimicking a production setup without the associated risks. The CP Sandbox provides an environment built with Docker Compose, allowing for easy setup and management of multi-container applications, while the CP-Ansible Sandbox automates the deployment process using Ansible playbooks, ensuring consistency and efficiency. Whether you’re a seasoned Kafka administrator looking to sharpen your troubleshooting skills or a developer wanting to experiment with Kafka configurations, these sandboxes provide the tools and scenarios necessary for mastering Kafka management. Through practical exercises and real-world scenarios, you’ll gain invaluable experience in diagnosing and resolving issues, ultimately preparing you for the complexities of managing Kafka in a production environment. So, dive into the CP Sandbox and CP-Ansible Sandbox, explore the various troubleshooting scenarios, and harness the power of these tools to enhance your Kafka expertise. Happy Kafkaing! --- # Unlocking The Potential of Local Kafka URL: https://platformatory.io/blog/Unlocking-the-Potential-of-Local-Kafka/ Published: 2024-07-30 Authors: Subramanya Madhyastha Categories: Kafka, Local Development, Docker Introduction Apache Kafka is a distributed streaming platform widely used for building real-time data pipelines and streaming applications. While cloud-based Kafka services are available, setting up Kafka locally offers a range of benefits, especially for development and testing. In this blog, we will explore why a local setup is beneficial, the various methods to achieve it, and provide a step-by-step guide for those methods and additionally we’ll be introducing few resources for setting up kafka locally, designed to simplify your testing and development processes, enabling you to deploy, manage, and monitor Kafka clusters efficiently on your local machine Problem Statement When working on small tasks and testing in cloud environments, developers often face significant challenges. Initial Setup Time: Provisioning a Kafka cluster can take considerable time, especially for initial setups. For example, deploying a managed Kafka service (MSK) using AWS CDK can take around 20 minutes for the first run​ (GitHub). This setup time is comparable across other major cloud providers such as Azure and Google Cloud Platform (GCP). Cluster Creation: Provisioning a Kafka cluster typically takes longer compared to producing/consuming messages. Creating a Kafka cluster on Confluent Cloud involves provisioning the necessary infrastructure and configuring settings. According to Confluent, this process takes approximately 10 minutes for a standard three-broker cluster. Produce/Consume Messages: These involve the actual use of the resources, such as producing and consuming messages, and typically have very low latency, often under 10 milliseconds for individual operations. Message Latency: The 99th percentile end-to-end latency (p99 E2E latency) for Confluent Cloud is generally low, with measurements such as 42 milliseconds at 10 MBps throughput and up to 73 milliseconds at 1.4 GBps throughput​ (Confluent)​. Frequency of Occurrence: Although the significant time investment is primarily during the initial setup. Once the infrastructure is in place, making minor adjustments or running tests is faster, although any changes that require re-provisioning of resources will still take time. The above timeframes of the Cluster creation and Producing/Consuming messages highlight the difference between setting up resources and using them, illustrating why developers might prefer local setups for rapid iterations and tests. Why Set Up Kafka Locally? Development and Testing: Local setups allow for rapid development cycles and immediate testing without the latency or cost implications of cloud services. Platform Independence: Using Docker and Docker-Compose, a local Kafka setup can be made platform-independent, allowing you to develop and test on any machine without worrying about compatibility issues. Greater Control: A local setup provides direct access to Kafka’s components, enabling finer-grained control over configuration, logging, and monitoring, which is essential for complex event-driven architectures. Cost-Effective: Eliminates the need for cloud resources, making it cost-effective, especially for small teams or individual developers and when developers forget to delete the resources. Methods for Setting Up Kafka Locally Manual Installation: Downloading and configuring Kafka and Zookeeper manually on your machine. This method provides deep insights into Kafka’s workings but is time-consuming. After downloading and configuring Kafka and Zookeeper (deprecated since 3.5 and removed in 4.0) manually on your machine, you can create a cluster by starting multiple instances of Kafka and Zookeeper on different ports. Refer the official Apache Kafka Documentation for a step by step guide: Apache Kafka Quickstart Using Package Managers: Using tools like Homebrew for macOS and similarly apt and choco for Linux and Windows respectively for installation can simplify the installation process. After installation to create a Kafka cluster, similarly to the manual installation you need to start multiple instances of Kafka brokers with different configurations. Docker: Using Docker to containerize Kafka and Zookeeper, making the setup process quicker and consistent. Docker provides a portable and lightweight environment that ensures your Kafka setup works the same way across different systems. Docker Compose: Docker Compose further simplifies this process by allowing you to define and manage multi-container Docker applications. With a single YAML file, you can specify the services, networks, and volumes required for Kafka and Zookeeper, making it easy to deploy and manage your Kafka environment consistently across different development and testing setups. Preferred Method for Local Installation Using Docker Compose to set up Kafka locally is the best approach out of these due to its consistency, ease of use and scalability i.e the ability to easily adjust the number of Kafka and Zookeeper instances, allocate appropriate resources, manage deployments efficiently, and ensure consistent performance and isolation across different environments. Manual Installation and Installation via Package Managers are relatively the same, as using a Package manager just eliminates the step of downloading the installation file manually, both the methods lack the portability and consistency that Docker offers, making them less ideal for replicating environments across different machines, and Setting up and configuring each instance manually or via package managers is time-consuming and prone to errors. Hence Docker Compose’s ability to provide a consistent setup across different machines, along with powerful tools for monitoring and troubleshooting, makes it the ideal solution for running Kafka locally. So how do you make use of a Local kafka Setup? At Platformatory, we leverage Kafka Sandbox which is setup locally and use it for testing and troubleshooting processes. The Kafka sandbox is an isolated environment mimicking a cloud setup using a docker-compose setup, along with Prometheus and Grafana deployed for observability and debugging there by achieving all these without the overhead of cloud infrastructure. What are the benefits of using the Sandbox? Realistic Testing and Performance Tuning: The benefit of having a setup similar to Production Environment is you can accurately simulate how Kafka and associated services will behave under real-world conditions to a certain degree and Potential issues and bugs can be identified and resolved before they impact the production environment. We can conduct performance and load testing to understand how the system scales and performs under various conditions, and fine-tuning the configurations and resource allocations in the sandbox according to the performance can help optimize the production setup. Monitoring and Metrics: By integrating Prometheus and Grafana, we continuously monitor Kafka’s performance, health and allows us to observe the cluster performance when we experiment with the configuration changes and also helps us to proactively identify and address any potential bottlenecks or issues. Configuration Management: The sandbox uses properties files mounted as volumes, which helps replicate certain aspects of a VM or bare-metal server environment. This includes persistent configuration management and network settings that provide isolation and resource allocation similar to traditional server setups. This allows us to manage configurations easily and consistently across different environments. However, it is essential to note that containers do not completely replicate the behavior of VMs or bare-metal servers, particularly regarding hardware interaction and persistent storage. Using the Confluent Platform (CP) Sandbox The CP sandbox is built using Docker Compose, which allows us to define and run multi-container Docker applications. Docker-compose file for Confluent Kafka with configuration mounted as properties files, brings up Kafka and components with JMX metrics exposed and visualized using Prometheus and Grafana. The environment simulates running Confluent Platform on VMs/Bare metal servers using properties files but using docker containers. Access the CP-Sandbox repository from here. The cluster contains the following resources deployed: 1 Zookeeper 3 Kafka Brokers LDAP Server Control Center Kafka Client Container Prometheus and Grafana Check the kafka server.properties for more details about the configurations of the setup. Running the CP Sandbox Clone the Repository: Start by cloning the repository containing the Docker Compose file and configuration files, you can access the repository via this link. 1 git clone git@github.com:Platformatory/cp-sandbox.git 1 cd cp-sandbox Start the Services: Use Docker Compose to start all the services defined in the docker-compose.yml file. 1 docker-compose up -d This command will bring up a three-node Kafka cluster with security enabled, along with other components like Zookeeper, Schema Registry, Kafka Connect, Control Center, Prometheus, Grafana, and OpenLDAP. There is a main branch and 12 Branches that are each troubleshooting scenarios for you to switch between and attempt. Check Service Status: Verify that all services are up and running. 1 docker-compose ps -a Ensure there are no exited services and all containers have the status Up. Conclusion Setting up Kafka locally unlocks immense potential for developers, offering a swift, cost-effective, and controlled environment for development, testing, and troubleshooting. Whether you choose manual installation, package managers, or Docker Compose, a local Kafka setup can significantly enhance your development workflow. Among these methods, Docker Compose stands out for its consistency, scalability, and ease of use, making it the ideal solution for running Kafka on your local machine. By using the CP Sandbox, you can efficiently set up, manage, and gain insights into troubleshooting Kafka clusters. The troubleshooting scenarios in the repository allow you to practice and resolve potential production issues in a controlled environment. Sounds interesting? If you wish to know more, take a look at our next blog titled “Learning by Debugging: Kafka Local Setup” where we dive deeper into troubleshooting scenarios and make use of the monitoring tools like Grafana which is deployed along with the Sandbox and how to set them up. In the next blog we also take a look at CP Ansible Sandbox, a setup which can be used for automated deployment and management of Confluent Platform clusters. --- # Authentication to Confluent Cloud Using OAuth/OIDC with Auth0 as Identity Provider URL: https://platformatory.io/blog/Configuring-OAuth-and-OIDC-for-Confluent-Cloud-using-Auth0/ Published: 2024-07-30 Authors: Vikhyat Shetty Categories: Security, Confluent Cloud, Kafka Configuring OAuth/OIDC for Confluent Cloud using Auth0 In the early days of the internet, sharing information between services was straightforward but risky. Users often had to share their usernames and passwords, exposing their credentials to potential misuse. Today, we have secure standards like OAuth 2.0 and OpenID Connect (OIDC) that make this process safer and more efficient. The popularity of OAuth and OIDC for authentication and authorization says a lot about the importance of the technology. If you see a login page online on a modern website, it is most likely configured using OAuth 2.0 and OpenID Connect (OIDC). These protocols have become the standard for secure, robust authentication and authorization across various applications and services. The Problem with Sharing Credentials Back in the day, if you wanted a service to access your information on another platform, you had to share your username and password. This practice was insecure for several reasons: No guarantee that the service would keep your credentials safe. No control over how much of your personal information the service could access. Thankfully, standards like OAuth 2.0 have been developed to address these security concerns. Understanding OAuth and OIDC: A Simple Example OAuth and OIDC work together to make secure logins easy and seamless. Imagine you want to log in to a new app using your Google account. When you click “Log in with Google,” OAuth handles the authorization by asking Google for permission to share your info with the new app. If you agree, OIDC comes into play, providing the app with your identity details, such as your name and email address, so you can log in without creating a new account. This way, OAuth ensures your data stays secure, and OIDC confirms your identity. For more information on OAuth and OIDC go through this beautifully explained blog post from Okta: An Illustrated Guide to OAuth and OpenID Connect Scope of this blog In this blog post, we will walk through the steps of configuring Auth0 as an identity provider for Confluent Cloud. Auth0 is a flexible, drop-in solution to add authentication and authorization services to your applications. Confluent Cloud is a fully managed event streaming platform based on Apache Kafka. By integrating Auth0 with Confluent Cloud, you can enhance the security of your Kafka clusters and streamline the user authentication process. Configuring Auth0 as an identity provider in Confluent Cloud Prerequisites: A Confluent Cloud account. An Auth0 account. Administrative access to both platforms. Steps: 1. Create a New Application in Auth0 Log in to Auth0: Go to your Auth0 dashboard. Create a New Application: You can see a Create Application button on the getting started page as shows in this picture or alternatively you can go to the application section on the left side of the screen and create an application from there Both options should land you in this page where you give your application details. Here you give your application name, and select Machine to Machine under application type.  Below this there is an option to select an API. I will be selecting the default Auth0 Management API in this example. But you can create your own API using the APIs section from the menu. Once we’ve selected the API, now we can select the permissions (scopes) we want this API to use. In this case, I am selecting all permissions. Click on continue to successfully create the Application Check Application Settings: In the application settings, take note of the Client ID and Client Secret. 2. Configure Auth0 as an Identity Provider in Confluent Cloud Log in to Confluent Cloud: Go to your Confluent Cloud dashboard. Navigate to Identity Providers: Go to the Accounts and access section Navigate to the Workload Identities tab Add a New Identity Provider: Click on Add Identity Providers. Choose Other OIDC Provider as the provider type. Fill in the Identity Provider Details: Fill in the Name, Description, OIDC Discovery URL, Issuer URI, JWKS URI as shown in the picture below. You might be wondering where to find these details. Well, the OIDC Discovery URL can be found under your application settings mentioned as Domain The issuer URI and and JWKS URI can be found in the OpenID Connect (OIDC) discovery documents found here: https://{yourDomain}/.well-known/openid-configuration In my case, it looks something like the image shown below Once this is filled, click on Validate and Save 5) Add Identity Pool: Once the Identity provider is created, we need to create an Identity pool. Cick on Add Identity Pool button as shown below Fill in the details as per your requirement. I have filled it as shown in the picture. You can use an identity pool to provide granular control over access of your applications to your Confluent Cloud resources. An identity pool is a group of external application identities that are assigned a certain level of access based on a claims-based policy For details on identity pool and how to use it, Check out Use Identity Pools with Your OAuth/OIDC Identity Provider on Confluent Cloud. Click next once you are done with populating the fields. Since we are creating everything from scratch we will select Add new permissions as shown below and hit next. On the next page, select the cluster you want to and give the permissions required and finish the setup. 3. Configuring Kafka Client Open your terminal from where you are trying to access the confluent cloud and where your client is present. Create a client configuration, in my case I have named it client.properties Use the following template to fill in your details  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 # Kafka Broker Connection bootstrap.servers=YOUR_BOOTSTRAP_SERVER # Security Protocol security.protocol=SASL_SSL # OAuth2 Token Endpoint URL sasl.oauthbearer.token.endpoint.url=YOUR_TOKEN_ENDPOINT_URL # Login Callback Handler Class sasl.login.callback.handler.class=org.apache.kafka.common.security.oauthbearer.secured.OAuthBearerLoginCallbackHandler # SASL Mechanism sasl.mechanism=OAUTHBEARER # JAAS Configuration sasl.jaas.config= \ org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule required \ clientId='YOUR_CLIENT_ID' \ clientSecret='YOUR_CLIENT_SECRET' \ extension_logicalCluster='YOUR_LOGICAL_CLUSTER' \ extension_identityPoolId='YOUR_IDENTITY_POOL_ID' \ scope='YOUR_SCOPES' \ audience='YOUR_API_IDENTIFIER'; In my case, I have used the following config 1 2 3 4 5 6 7 8 9 10 11 12 bootstrap.servers=pkc-p11xm.us-east-1.aws.confluent.cloud:9092 security.protocol=SASL_SSL sasl.oauthbearer.token.endpoint.url=https://dev-jpup1hj0aphkbijm.us.auth0.com/oauth/token sasl.login.callback.handler.class=org.apache.kafka.common.security.oauthbearer.secured.OAuthBearerLoginCallbackHandler sasl.mechanism=OAUTHBEARER sasl.jaas.config= \ org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule required \ clientId='8GJmNPXY5UV1yrSNgc1ggiKkYcHiifFM' \ clientSecret='wSQzDaI-MRB80w2HyzKbV-JjPS4Ijd5zUu10LdisgEDR7_LRoC98ruBGgnLd_Lha' \ extension_logicalCluster='lkc-37vn0o' \ extension_identityPoolId='pool-AXqR' \ scope='read:users'; Note that, you should never share your client details, especially the client secret. I have deleted all instances of my application, hence I haven’t redacted the client secret. Here we can add as many permissions as we want to access under the scope parameter. But this can be done only if we have allowed the access in the identity pool. We can use this client.properties to access the kafka cluster depending on the amount of permissions we have. Conclusion In conclusion, integrating Auth0 as an identity provider for Confluent Cloud significantly enhances the security and efficiency of your Kafka clusters. By leveraging the power of OAuth 2.0 and OpenID Connect, you can ensure that user credentials are protected, and access is precisely controlled. This setup not only streamlines the authentication process but also provides a robust framework for managing permissions and identities. As you follow the steps outlined in this guide, you’ll find that configuring Auth0 with Confluent Cloud is straightforward and highly beneficial for maintaining a secure, scalable, and user-friendly environment for your event streaming applications. --- # Monetizing APIs, Data through usage-based billing URL: https://platformatory.io/blog/Why-Real-time-API-Monetization-is-the-need-of-the-day/ Published: 2024-07-29 Authors: Ashwin Venkatesan Categories: API Management, SaaS, Real-time, Cost Introduction APIs (Application Programming Interfaces) have become one of the most important components of modern digital applications. They allow developers to quickly and easily integrate different services into their applications, making them more powerful and efficient. In a constantly evolving digital economy, APIs are necessary to continuously enable new services, but the need for digital-first strategies have made APIs more of a priority than ever before. Every organization is confronted by the need to make changes fast and adapt to new ways of conducting their business. APIs streamline this process of transformation. APIs Beyond Plain Old Integration In the early days, APIs (Application Programming Interfaces) served a straightforward purpose: to enable communication between frontend and backend systems or to facilitate information exchange between internal services. However, as technology has advanced and businesses have evolved, so too have APIs. Today, they are the backbone of complex interactions across distributed systems, supporting real-time data processing, microservices architectures, and seamless connectivity with third-party services and platforms. This evolution has transformed APIs from simple integration tools into critical enablers of digital transformation. The Natural Evolution of APIs: From Endpoints to Marketplaces The journey of APIs can be mapped out in four distinct stages: Endpoints: Initially, APIs were mere endpoints—interfaces that allowed different software applications to communicate. Products: As the benefits of APIs became more apparent, they began to be developed as products. These productized APIs were designed with a focus on usability, documentation, and developer support. Companies started to offer APIs as standalone products that could be consumed by external developers to build new applications and services. Platforms: The next stage in the evolution saw APIs becoming integral to platform-based business models. Companies like Amazon, Google, and Facebook built extensive ecosystems around their APIs, enabling third-party developers to create applications that extended the functionality of their platforms. This shift transformed APIs into powerful tools for ecosystem building and innovation. Marketplaces: Today, APIs are at the heart of digital marketplaces. These marketplaces provide a centralized location where developers can discover, evaluate, and purchase APIs from various providers. By monetizing their APIs, companies can generate new revenue streams and foster a thriving developer community. Company as a Service In the current digital landscape, companies are leveraging APIs to offer their core capabilities as services. This “company as a service” (CAAS) model allows businesses to expose their internal processes and data to external developers, partners, and customers through APIs. By doing so, they can create new business opportunities, improve operational efficiency, and drive innovation. For instance, a logistics company might expose its shipment tracking API to e-commerce platforms, enabling real-time tracking for customers. Similarly, a financial institution could offer APIs for payment processing, account management, and fraud detection, allowing fintech startups to build innovative solutions on top of their infrastructure. The API Economy: High Valuations and Strategic Acquisitions The evolution of the API economy is evident in the high valuations of companies like Stripe and Solarisbank. These companies have built their success on the strength of their APIs, offering robust and reliable services that are easy to integrate and use. Stripe’s APIs, for example, have revolutionized online payments, making it simple for businesses of all sizes to accept payments over the internet. Established companies in major economic sectors, particularly fintech, are also recognizing the power of APIs. They are either building platform-based business models that leverage APIs to become leaders in their space or acquiring third-party companies to expand their API-based services. This strategic approach enables them to drive innovation, enhance customer experiences, and stay competitive in a rapidly changing market. The Federated Future of API Management While HTTP-based APIs have traditionally dominated the conversation, the reality is that APIs are not restricted to a single protocol. Data APIs, along with various other protocols and interfaces, have become widespread, reflecting the diversity and complexity of the systems they serve. As data emerges as the most valuable asset for organizations, managing these APIs has become both more critical and more challenging. The Expanding Universe of APIs APIs today are not just about HTTP. They encompass a wide range of protocols and interfaces, each serving specific purposes and optimizing different aspects of data and service interaction. Here are a few examples: gRPC: An open-source remote procedure call (RPC) system that allows clients and servers to communicate transparently. WebSockets: A protocol providing full-duplex communication channels over a single TCP connection, ideal for real-time applications. PostgreSQL: Not just a database but also a protocol for managing relational data. S3: Amazon’s Simple Storage Service, which has its own API for object storage. HDFS: The Hadoop Distributed File System, essential for managing large-scale data storage across clusters. Cassandra: A distributed NoSQL database with its own API for handling large amounts of unstructured data. The Heterogeneous Interface Landscape The interface for exposing services has become highly heterogeneous. This diversity is not limited to the protocols mentioned above but extends across various deployment environments: Public Clouds: Services hosted on platforms like AWS, Azure, and Google Cloud. Private Clouds: Dedicated cloud infrastructure managed by organizations. On-Premises: Traditional data centers still play a crucial role in many industries. Edge Computing: Computing resources located closer to the data source to reduce latency and improve performance. This heterogeneity in interfaces and deployment environments presents a significant challenge: managing this sprawling landscape with a single, monolithic API management system is impractical and inefficient. Beyond Monolithic API Management The classic approach to API management, which often revolves around HTTP proxies and centralized cataloging, is increasingly inadequate for today’s needs. Here’s why a federated approach is essential: Decentralized Control: In a federated system, each API can be managed independently, allowing for greater flexibility and responsiveness. This is particularly important in hybrid environments where services may span public clouds, private clouds, and on-premises infrastructure. Protocol Agnosticism: A federated system can support a wide range of protocols, ensuring that the most appropriate and efficient protocol is used for each specific case. This avoids the one-size-fits-all approach of traditional systems. Scalability: Managing APIs in a decentralized manner allows organizations to scale their API infrastructure organically. Each service or application can be scaled independently, optimizing resource usage and performance. Resilience and Redundancy: A federated approach enhances system resilience by avoiding single points of failure. If one API endpoint or management system goes down, others can continue to operate unaffected. Embracing the Sprawl Given the decentralized nature of modern API ecosystems, the concept of a central catalog is becoming outdated. Instead, organizations should focus on creating interconnected catalogs and discovery mechanisms that can operate across diverse environments. This can be achieved through: Service Meshes: Tools like Istio or Linkerd that manage microservices communication, providing visibility and control over diverse API traffic. API Gateways: Deploying multiple API gateways closer to where the services reside, whether in the cloud, on-premises, or at the edge. Federated Catalogs: Implementing catalogs that can sync and interoperate, providing a comprehensive view of APIs without centralization. Unlocking the Full Potential of Your API Program The technical aspects of API development are well understood but the business potential of APIs remains underexploited. According to a 2023 Kong Customer Survey, 46% of developers say senior leadership lacks a strong understanding of the value of APIs. This divide can have implications for organizations striving to harness the full potential of APIs by embracing an API-first approach. It’s time to elevate API productization and monetization to a first-class feature of API offerings. Revenue: The Ultimate Measure of API Success When evaluating the success of an API program, revenue stands out as the most definitive metric. In the business world, Profit and Loss (P&L) is the language that speaks volumes about the effectiveness of any initiative. For API programs, revenue generation should be a central focus, not an afterthought. However, most API management platforms currently overlook this crucial aspect. The Overlooked Aspects in API Management Platforms API management platforms provide tools for API creation, deployment, and monitoring but often fall short in offering robust features for productizing and monetizing APIs. To bridge this gap, API product managers need a comprehensive approach that considers the following factors: 1. A Unified View Across Your API Real Estate To effectively productize APIs, it’s essential to have a holistic view of your entire API ecosystem. This includes discovering and cataloging all available APIs, understanding their usage patterns, and identifying opportunities for monetization. A comprehensive API inventory is the first step towards a successful monetization strategy. 2. A First-Class POV on Developer Experience (DevX) Developer Experience (DevX) is a critical factor in the success of any API product. A positive DevX ensures that developers can easily discover, understand, and integrate APIs into their applications. This involves providing clear documentation, robust SDKs, and responsive support. Investing in DevX not only attracts more developers but also increases the likelihood of successful API adoption and monetization. 3. Empirical Product Market Fit: Will People Even Use It? Before monetizing an API, it’s crucial to validate its product-market fit. This involves conducting market research to understand the needs and pain points of potential users. By gathering empirical data and feedback from developers, API product managers can refine their offerings to better meet market demands. Understanding whether there is a genuine need for your API is a prerequisite for successful productization. 4. Price Discovery: Will People Pay for It? Once product-market fit is established, the next challenge is price discovery. Determining the right pricing model for your API is critical to maximizing revenue. This could involve usage-based pricing, subscription models, or tiered pricing plans. Conducting market research and competitive analysis can help identify the optimal pricing strategy. Additionally, offering flexible pricing options can cater to different segments of your target audience, increasing the likelihood of monetization success. The Growing Market for API Monetization Platforms The importance of API monetization is underscored by the impressive growth projections for the API monetization platform market. FMI predict a compound annual growth rate (CAGR) of 28.1% during the forecast period 2023-2033, with the industry expected to generate US$ 6.1 billion in 2023 and exceed US$ 72.6 billion by 2033. This rapid growth reflects the increasing reliance on APIs by large companies, with approximately 40% of them using hundreds of APIs in their daily operations. Furthermore, an estimated 71% of developers plan to leverage APIs to a greater extent in the coming years. According to Kong API Impact Report, by 2027, APIs are projected to contribute a staggering $14.2 trillion to the global economy. That’s a projected $3.3 trillion growth in market size from 2023 — a difference greater than the current GDP of the United Kingdom or France. API Monetization: Key Considerations for Success Here are key considerations for effectively monetizing your API: Metering Layer The API layer can capture and collect data on API usage, performance metrics, and error handling for monitoring, analytics, generating insights about API usage patterns, identifying bottlenecks, or optimizing system performance. So, an API layer remains the most ideal place to record and meter transactions. Ensuring accurate and asynchronous recording of metrics is crucial. This allows for precise tracking of usage, which is essential for billing and analyzing customer behaviour. Choosing the Right Usage Metric Selecting the appropriate usage metric is vital for aligning your API’s value with customer needs. The business capability delivered by the API should be quantified in terms that are meaningful and self-evident to the user. Instead of focusing solely on API call volumes, maybe consider metrics such as: Transaction volume: Number of transactions processed. Data volume: Gigabytes of data sent or received. Unique users: Number of distinct users accessing the API. Imagine this: billing based on the number of sequences stored in an email marketing tool might not be logical. Why? Customers might keep deleting sequences after sending them. A smarter approach? Gauge the number of unique contacts emailed every month or the total emails sent out. The choice of metric should depend on the specific product or service offered and the typical behaviour of your customers. Billing Model: Prepaid vs. Postpaid Choosing between prepaid and postpaid billing models involves understanding your customers’ preferences and cash flow considerations. Prepaid: Customers pay upfront for a set amount of usage. This model is straightforward and ensures immediate revenue, but may require customers to estimate their usage accurately. Postpaid: Customers are billed based on actual usage after the fact. This can be more flexible and attractive to customers, but poses a risk of delayed payments and bad debt. Pricing Strategy: Tiered Pricing vs. Pay As You Go A well-thought-out pricing strategy can significantly impact your API’s adoption and profitability. Tiered Pricing: Offers different pricing tiers based on usage levels. This model can cater to a wide range of customers, from small startups to large enterprises. It provides predictability and scalability. But sometimes, the price doesn’t resonate with what your customers feel they’re getting. Too many tiers? They might just freeze, unsure of which to pick. Pay As You Go (Usage based billing): Charges customers based on actual usage. This model is highly flexible and can be appealing to businesses that prefer to pay for only what they use. It can also encourage more usage as there are no upfront commitments. Invoice Methods: Recurring Invoicing vs. Threshold-Based Invoicing Invoicing methods should align with your billing strategy and customer preferences. Recurring Invoicing: Bills customers at regular intervals (e.g., monthly, quarterly). This method is predictable and can simplify budgeting for both the provider and the customer. Threshold-Based Invoicing: Bills customers once they reach a certain usage threshold. This can be effective for usage-based models, ensuring that customers are only billed when they have consumed a significant amount of the service. Focus on Business problems rather than technical problems A common challenge for SaaS and PaaS companies is focusing on building metering and billing systems, often at the expense of identifying and pricing their API products effectively. Focus on Core Strengths: Rather than developing complex metering and billing UIs, leverage third-party solutions that specialize in these areas. This allows your team to focus on refining the API products themselves. Market-Driven Solutions: Allow the market to choose the best experience layer, rather than trying to build a one-size-fits-all solution. This can lead to better user experiences and more robust solutions. Don’t cannibalize the customers. Economy of Scale: By focusing on your core strengths and leveraging specialized providers for billing and metering, you can achieve better economy of scale and allocate resources more efficiently. Apinomy - API (Data) Monetization at Scale Apinomy enables direct monetization of your APIs and Data, at scale. Helps you in enabling internal, external and 3rd party developers to subscribe to your APIs and Data, with unlimited flexible plans, designed by you. Apinomy is not an API management platform by itself, but it supports the majority of API platform providers, including Kong, Apigee, Envoy, AWS API Gateway and more. It is simple enough for anyone to build a gateway plugin, based on the capabilities of the gateway. Apinomy works by integrating with your gateway to do the following things: Discover APIs (that is endpoints: hosts, routes, even upstream services and event OpenAPI specs, based on support) Then, it allows you to bundle these APIs into meaningful products. Then, you can create attractive usage based billing models. General models include tiered pricing based on API call volumes, but Apinomy also allows you to define your custom service units. For example, you could define an API plan to be billed against a custom metric, such as SMS API to be billed against number of messages sent, or a payment transaction to be billed against the value of the transaction. Your users can either subscribe to these products through the available rate plans from the default portal that Apinomy provisions, or can also be integrated with your own portal. Rate plans can be prepaid for a licensed usage quota as well. Apinomy, collects logs from the gateway in near real-time and aggregates these in real-time to generate usage reports as well as billing to the bound of a minute. Apinomy seamlessly integrates with the billing solution of your choice: Stripe, Chargebee etc. In fact, this is only a fraction of what you can achieve with Apinomy. Over and above this, you can also use Apinomy as an ecosystem platform, to organize your APIs into multiple domains, products and to govern your ecosystem at large. To know more about how Apinomy works, take a look the demo video. We believe Apinomy will be useful for a variety of data & API monetization use-cases at large, but it also usable for other concerns such as, SaaS usage based billing - Bill tenants based on API calls. Simplify Fin-ops with tenant level insights on usage against revenue Chargeback for Internal Platforms - Gain insight into BU + charge-code level usage for shared services SaaS and COTS platforms API Marketplace - Run your own API Marketplace with API producers, developers (internal, external, partners) as constituents enabling various monetization models Future versions of Apinomy will also support data monetization around the Postgres protocol. We will have more exciting news. But for now, Apinomy provides very exciting opportunities in real-time billing for APIs and is the only multi-gateway, multi-cloud usage billing product. This enables creating a comprehensive monetization and revenue plane for your APIs. Conclusion Real-time API monetization is critical for organizations looking to unlock new revenue streams and drive innovation. With tools like Apinomy, businesses can effectively manage, productize, and monetize their APIs across multiple platforms and environments. By focusing on meaningful metrics, flexible billing models, and a strong developer experience, companies can harness the full potential of their API programs and stay competitive in a rapidly evolving market. As the API economy continues to grow, businesses that embrace real-time monetization will be well-positioned to capitalize on emerging opportunities and sustain long-term success. --- # Tooling and Process: Lessons from running Kafka at scale for mission critical customers URL: https://platformatory.io/blog/Tooling-and-Process-Lessons-from-running-Kafka-at-scale-for-mission-critical-customers/ Published: 2024-07-29 Authors: Arun B Bhat Categories: Kafka Operations, Kafka, SRE, Performance Introduction In today’s digital economy, data is the lifeblood of business operations. Companies rely on real-time data processing to make informed decisions, optimize operations, and enhance customer experiences. Apache Kafka has emerged as a critical component for enabling the efficient handling of vast amounts of data. However, running Kafka at scale for mission-critical businesses presents unique challenges and opportunities. After choosing Kafka to streamline data connectivity, the next major task is efficient operation. This article delves into the potential challenges, strategies for mitigating them, and tools that can streamline the operational management of Kafka clusters at scale, ensuring reliability and performance. Understanding the Scale of Kafka Deployment in Mission Critical Environments Before deploying Apache Kafka at scale, especially for mission critical applications, understanding and managing various environments like Development (Dev), Pre-Production (Pre-Prod), Disaster Recovery (DR) and Production Environments is essential before deploying Apache Kafka at scale. Each environment serves a unique purpose, and balancing their needs can help ensure that Kafka deployments are reliable, resilient, and efficient. Here, we delve into the roles of Dev, Pre-Prod, DR and Production Environments which is commonly seen architecture in critical deployments. This architecture is commonly seen in critical deployments, although it may vary based on specific organizational requirements. Dev Environment The Dev environment is where developers experiment with new ideas, write code, and test features in isolation. It provides a sandbox for innovation without affecting production or PreProd environments. CI/CD Pipeline Integration: Any changes, such as version upgrades or new configurations, should first be applied in the Dev environment. Here, they undergo initial testing and validation to ensure they don’t introduce any issues. This process should be managed through an automated CI/CD pipeline that ensures consistency and speed. PreProd Environment The PreProd environment is a staging ground for testing new features, configurations, and updates before they go live in production. It mimics the production environment to identify potential issues and ensure changes don’t negatively impact live operations. CI/CD Pipeline Integration: After successful testing in the Dev environment, the changes should automatically be promoted to the PreProd environment via the CI/CD pipeline. Here, the changes are subjected to further testing, including performance and integration testing, to validate their readiness for production. Disaster Recovery Environment: The DR environment is a backup setup designed to mirror the production environment. It serves as a failover solution to maintain business continuity in the event of outage in the production environment. The DR environment utilizes Kafka’s MirrorMaker2/Cluster linking or other replication tools to synchronize data between the production and DR clusters. It is designed to quickly assume production workloads with minimal downtime, ensuring that business processes remain uninterrupted. CI/CD Pipeline Integration: Once the changes have been thoroughly tested in the PreProd environment, the CI/CD pipeline automatically deploys them to the DR environment. This ensures that the DR setup is always in sync with production and ready to take over if needed. Production Environment The production environment is the live setting where Kafka processes real-time data for business operations. It must handle high throughput, low latency, and provide seamless data streaming capabilities to support mission-critical applications. While environments provide the framework for Kafka deployments, it is important to recognize potential pitfalls within a Kafka cluster that can impact its performance and reliability. CI/CD Pipeline Integration: After passing all previous stages, the changes are finally deployed to the Production environment through the CI/CD pipeline. This controlled, step-by-step deployment process minimizes risks and ensures that the production environment remains stable and reliable. Operational Challenges Establishing the appropriate Kafka infrastructure is one thing, but ensuring its smooth operation is an entirely different challenge. Below are some common issues that may arise during its operation. Network Network issues can significantly impact the performance and stability of a Kafka cluster. Here are some specific network related problems that might arise: Increased Latency: Network issues can cause delays in data transmission between producers, brokers, and consumers, slowing down message delivery and retrieval, which affects the overall performance of the Kafka system. Key node metrics like transmit_queue_length, receive_queue_length, receive_drop_total, and transmit_drop_total are useful for detecting and analyzing such issues. Packet Loss: Loss of network packets may lead to incomplete or missing messages, resulting in data loss or corruption. Key node metrics like receive_errs_total, transmit_errs_total can be used to detect such issues. Broker Connectivity Problems: Brokers may have difficulty communicating with each other or with producers and consumers due to network problems. This can lead to failed replication, partition reassignments, or difficulties in maintaining cluster health. Persistent network issues can contribute to broker failures. Monitoring kafka metrics such as kafka_server_KafkaRequestHandlerPool_RequestHandlerAvgIdlePercent, kafka_network_SocketServer_NetworkProcessorAvgIdlePercent can help in diagnosing and measuring these issues. Network Partitioning: Network partitioning, where different parts of the Kafka cluster become isolated from each other, can cause inconsistencies and disruptions in data flow. This can lead to unavailability of data or inconsistent states across the cluster. Kafka metrics like ActiveControllerCount can help in identifying this issue. DNS Resolution Issues: Problems with DNS resolution can prevent clients from locating Kafka brokers, leading to connection failures and interruptions in service. By monitoring node metrics like dns_resolver_failures_total we can identify these issues. Network Configuration Errors: Incorrect network configurations, such as misconfigured IP addresses, firewalls or security groups can lead to connectivity issues or network conflicts. Node metrics like network_iface_up can help identify this issue. Jitter: Variability in network delay (jitter) can affect the timing of message delivery and processing, impacting the consistency of data flow. We can rely on node metrics like network_receive_multicast_total and network_transmit_multicast_total to identify this issue. Input/Output Issues related to I/O (Input/Output) on a server running Kafka can significantly impact performance and stability. Here are some specific I/O-related problems that might arise: High I/O Latency: Increased latency in I/O operations can slow down read and write processes, leading to delays in message production and consumption. Node metrics like disk_io_time_seconds_total can help identify this issue. I/O Bottlenecks: Overloaded or slow disk subsystems can create bottlenecks, limiting the overall throughput and affecting Kafka’s ability to handle high data volumes efficiently. Monitoring node metrics such as disk_io_time_weighted_seconds_total, disk_io_now can help identify this issue. I/O Errors: Errors in I/O operations, such as read/write failures, can cause data corruption, incomplete writes, or read errors, affecting data integrity. Key node metrics like disk_errors_total can be used to detect this issue. I/O Saturation: Saturation of I/O resources, where the disk subsystem reaches its maximum capacity, can lead to delays and failures in processing Kafka messages. We can rely on node metrics like disk_saturation to identify this issue. High I/O Utilization: Excessive I/O usage can overwhelm the disk subsystem, leading to degraded performance and potential slowdowns in Kafka operations. Node metrics like node_disk_utilization can help identify this issue. Disk Storage When dealing with disk issues on a server running a Kafka broker, several specific problems might arise: Disk Failures: Physical disk failures or hardware malfunctions can render the disk inaccessible or cause data corruption. Node Metrics like disk_failed can be used to identify this issue. Disk Full: Running out of disk space can prevent Kafka from writing new data or appending to existing logs, potentially causing brokers to stop accepting new messages. We can set alerts on metrics like node_filesystem_avail_bytes to get notified when the disk space is low. Disk Corruption: File system corruption or sector damage can lead to corrupt log files, impacting data integrity and leading to errors during read or write operations. We can rely on node metrics like filesystem_readonly to identify this issue. Disk Fragmentation: Fragmented disks can result in slower read and write operations as the system struggles to access scattered data. Key node metrics like filesystem_fragmentation can help identify this issue. Memory Issues related to Memory can have a significant impact on the performance, reliability, and stability of a Kafka broker. Here are some common problems that can arise due to insufficient or mismanaged RAM in a Kafka setup: Out of Memory (OOM) Errors: When Kafka brokers run out of available memory, Java’s garbage collector cannot free up enough space to accommodate new objects, leading to java.lang.OutOfMemoryError. This can cause sudden shutdowns or crashes of the broker leading to potential data loss and disconnection of producers and consumers from the broker, causing disruptions in data flow. Node metrics like memory_OOM_kill can help identify this issue. High Garbage Collection (GC) Activity: Excessive or prolonged garbage collection cycles, where the JVM spends a significant amount of time in GC, impacting application responsiveness, increased latency, reduced throughput. We can rely on metrics like ava_lang_GarbageCollector_G1_Young_Generation_CollectionTime to identify this issue. Insufficient Page Cache: When Kafka brokers have limited RAM, the operating system’s page cache cannot cache log segments effectively, leading to increased disk I/O. Node metrics like memory_page_cache_utilization can be used to identify this issue. Swap Usage: High swap utilization occurs when the operating system moves pages from RAM to disk leading to severe performance degradation as accessing data from swap is much slower than from RAM. Monitoring node metrics like memory_SwapUsed_bytes can help identify this issue. Memory Leaks: Gradual increase in memory usage over time without release, eventually leading to exhaustion of available memory. Brokers may exhibit unpredictable behavior, leading to errors and inconsistencies. Observation of consistent decrease of node metrics like memory_MemAvailable_bytes can help identify this issue. CPU Usage Issues related to CPU usage can significantly affect the performance and stability of a Kafka broker. Here are some specific problems that might arise: High CPU Utilization: When CPU is highly taxed by kafka operation i.e often nearing 100% may lead to increased process latency for producer & consumer, reduced throughput and brokers may become unresponsive to requests, leading to timeouts and client disconnections. Node metrics like cpu_seconds_total{mode=”idle/system/user”} can help identify this issue. CPU Spikes: Sudden CPU spikes may lead to inconsistent performance like increased temporary latency, broker may temporarily become unresponsive affecting client operations. We can rely on Node metrics like cpu_seconds_total to identify this issue. CPU Contention: Multiple processes on the same server compete for CPU resources, usually caused by Co-location of other resource-intensive applications on the same server as Kafka, leading to contention and performance degradation. This can increase latency and inconsistency. Monitoring node metrics like cpu_cores_scheduled can help identify issues here. High Context Switching: Excessive context switching occurs when the CPU frequently shifts between tasks, leading to overhead and performance loss. This happens when a large number of active threads or processes are competing for CPU time. Node metrics like context_switches_total can help identify this issue. Client Side In a Kafka ecosystem, producers and consumers play crucial roles in sending and receiving data. However, misconfigurations, or poor implementation on the client side can lead to various problems. High Latency in Message Production: Producers experience delays in sending messages, causing a backlog. This can be caused due to inefficient batching due to poor configuration (‘batch.size’,’ ‘linger.ms’), Misconfigured max.in.flight.requests.per.connection leading to blocked requests etc. Kafka metrics like Kafka_producer_producer_metrics_record_send_latency_avg can help identify this issue. Load Imbalance Across Partitions: Uneven distribution of messages across partitions, leading to hotspots. This can be caused by poor key selection leading to uneven partition distribution. We can rely on kafka metrics like kafka_server_ReplicaFetcherManager_MaxLag to identify this issue. Incorrect Consumer Configuration: Consumers may fail to connect, consume messages incorrectly, or experience delays. This can be due to Incorrect bootstrap.servers or group.id configuration, misconfigured auto.offset.reset (e.g., earliest vs latest), Poorly configured session.timeout.ms and heartbeat.interval.ms etc. Monitoring kafka metrics like Kafka_consumer_consumer_coordinator_metrics_rebalancetime_avg can help identify this issue. Rebalancing Issues: Frequent consumer group rebalancing, leading to interruptions in message consumption. This can be due to Frequent changes in consumer group membership (e.g., adding/removing consumers), Incorrectly configured session.timeout.ms and heartbeat.interval.ms settings. Metrics like Kafka_consumer_consumer_coordinator_metrics_rebalancetime_max can help identify this issue. Key Practices for Efficient Kafka Cluster Operations Implementing CI/CD Architecture for Kafka Cluster Management Establishing a CI/CD architecture for Kafka cluster management is crucial for seamless upgrades and rollbacks. Version control is vital for managing Kafka configurations and ensuring consistency across environments. By centralizing essential Kafka files in a repository, you can streamline the upgrade process and reduce the risk of configuration drift. For instance, if Kafka is installed using Ansible, having the Ansible playbook readily available is critical for understanding the cluster’s setup and applying patches or upgrades in the future. A CI/CD pipeline using tools like Jenkins, Ansible can automate the deployment process, making it more efficient and less error-prone. This approach ensures that changes are tested, approved, and applied consistently across environments. Also when multiple teams collaborate on a Kafka cluster, changes made by one team can inadvertently affect the cluster’s stability. For example, if the infrastructure team updates or patches the Java installation on a server, it might impact the Kafka components running on that server. Implementing automated scripts as part of CI/CD pipeline to monitor and detect any software changes on the server can help identify potential problems early. These scripts can provide insights into configuration changes, missing dependencies, or unexpected software updates that may not have alerts set up. By ensuring the cluster’s health and consistency, you can maintain smooth operations and minimize disruptions. Effective Monitoring of kafka Cluster Monitoring Kafka clusters is crucial for maintaining smooth and efficient operations. By closely tracking key metrics, you can detect potential issues early and take corrective actions before they escalate into larger problems. To effectively monitor Kafka clusters, it is crucial to implement custom tooling solutions such as Prometheus-Grafana, Datadog, or New Relic. These tools provide comprehensive insights into the cluster’s health and performance, enabling proactive management. Configuring alerts for these critical metrics is equally important. Alerts should notify you before potential disasters occur, allowing you to address issues promptly. Managing alerts is very crucial to reduce Noisy alerts and false alarms. One way to manage alerts effectively is to differentiate between short-term and long-term issues. For instance, an alert for under-replicated partitions might be temporarily triggered if a Kafka broker node is restarted, which is a short-term issue since the partition will catch up once the broker restarts. However, the same alert becomes crucial if a broker goes down due to a more severe problem. Tools like Prometheus Alert Manager can be utilized to group and prioritize alerts, ensuring effective monitoring and rapid response to potential issues. Custom Tooling for Proactive Management It is well known that prevention is better than mitigation. Therefore, early detection and resolution of anomalies in a Kafka cluster is crucial. With this in mind, we designed and implemented operational tools for managing, monitoring, and securing Kafka clusters. Kafka-CP-Log-Monitor The Kafka-CP-Log-Monitor is a specialized tool designed to efficiently monitor and analyze Kafka component logs from a single, centralized location. By leveraging the ELK stack—Elasticsearch, Logstash, and Kibana—along with Filebeat, this tool provides a robust solution for collecting, parsing, and visualizing Kafka logs across multiple nodes. This tool addresses several challenges commonly faced when analyzing Kafka component logs. Key Features Centralized Log Collection: Filebeat is configured on each Kafka component to gather logs, which are then sent to Logstash for processing. This eliminates the need for manual log collection from individual servers. Log Parsing and Visualization: Logs are parsed using predefined configurations and are made available in the Kibana UI. Users can easily view and analyze these logs, gaining insights into Kafka’s performance and identifying potential issues. Addressing Common Challenges The Kafka-CP-Log-Monitor addresses several challenges that users often face when analyzing Kafka component logs: Access Permissions In multi-node Kafka deployments, sufficient permissions were required to SSH into component servers to access logs. The Kafka-CP-Log-Monitor eliminates this need by aggregating logs in a centralized location, streamlining access and improving security. Below is an image from a 3-node Kafka deployment, showcasing how all the broker and ZooKeeper logs are consolidated and visualized in a centralized place, providing a comprehensive view of the Kafka ecosystem. Reducing Time Overhead Fetching or viewing logs spread across multiple servers can be time-consuming. This tool reduces the overhead by providing a unified interface to access logs from different servers, saving valuable time and effort Log Searchability Searching for errors using grep in large log files is cumbersome and inefficient. With Kafka-CP-Log-Monitor, logs are searchable based on component type, hostname, log level, and more. This significantly speeds up the triage process and enhances the ability to diagnose and resolve issues quickly. The image below demonstrates how log entries can be filtered, showcasing a specific entry containing the phrase “Leader Imbalance Ratio.” Here is a demo of Kafka-CP-Log-Monitor. Kafka-CP-JMX-Monitor Kafka-CP-JMX-Monitor is a comprehensive tool designed to capture and visualize Kafka’s JMX metrics, offering deep insights into the health and performance of Kafka clusters. Key Features Capture JMX Metrics: Kafka-CP-JMX-Monitor captures critical JMX metrics exposed by Kafka and presents them as insightful graphs in customizable dashboards, facilitating detailed analysis of cluster operations. Prometheus and Grafana Integration: The tool integrates with Prometheus for scraping JMX metrics and uses Grafana to build and visualize dashboards based on the data collected. Grafana also supports configuring alerts based on these metrics. Advanced Alerting: Kafka-CP-JMX-Monitor provides advanced alerting capabilities, including anomaly detection and rate-of-change monitoring. This helps in proactive issue identification, trend analysis, capacity planning, and potential issue detection. System Metrics Monitoring: In addition to Kafka JMX metrics, the tool monitors system metrics of Kafka component servers through a node-exporter service, offering a comprehensive view of server performance. Addressing Common Challenges Comprehensive Cluster Visibility By capturing and visualizing JMX metrics, Kafka-CP-JMX-Monitor offers a clear view of the cluster’s operational health, enabling us to predict and address potential issues before they become significant problems. Below is a snapshot of some of the Kafka broker metrics as seen in the Grafana dashboard coming from the Prod environment. Efficient Capacity Planning The tool’s trend analysis and visualization capabilities aid in effective capacity planning and resource allocation, ensuring optimal performance and preventing resource shortages. Proactive Issue Detection Advanced alerting features help in detecting anomalies at both the cluster and individual node levels, drastically reducing the occurrence of major issues and improving overall cluster stability. Here is a demo of Kafka-cp-jmx-dashboard. Kafka-cp-deploy-manager “kafka-cp-deploy-manager” automates Kafka cluster lifecycle management, handling version upgrades, configuration changes, and scaling operations seamlessly. Key Features State Management: It maintains the state of the Kafka cluster at any given time, facilitating automated deployments that align with the desired state. Version Control: It uses a GitHub-like version control system to manage state files of the Kafka cluster, allowing for easy rollbacks if issues arise. Continuous Deployment with Jenkins: Jenkins handles continuous deployment based on state changes, simplifying deployment with configurable variables in an interactive UI and abstracting deployment complexity. Addressing Common Challenges Consistent and Reproducible Pipelines Kafka-CP-Deploy-Manager ensures uniformity in deployment processes, leading to consistent and reproducible pipelines. Error Mitigation The tool reduces human errors during deployment by automating and streamlining the process. Smooth Upgrades and Rollbacks Versioned state files facilitate smooth upgrades and rollbacks, maintaining stability throughout the deployment process. Privilege Isolation The tool segregates write and execute privileges, allowing administrators to manage state files while developers handle deployments. Here is a demo of Kafka-cp-deploy-manager. Conclusion Running Kafka at scale for mission-critical customers is both complex and rewarding. By mastering the Kafka ecosystem and adhering to best practices in sizing, tooling, deployment, and performance optimization, organizations can fully leverage Kafka’s potential. These tools have significantly enhanced our monitoring and management capabilities, contributing to a more efficient and reliable data streaming infrastructure --- # Seamless Authentication to Confluent Cloud Using OAuth/OIDC with Okta as Identity Provider URL: https://platformatory.io/blog/Use-OAuth-OIDC-to-Authenticate-to-Confluent-Cloud/ Published: 2024-07-24 Authors: Shivaprakash Akki Categories: Security, Confluent Cloud, Kafka OAuth2: Essential Insights You Should Know In the digital age, securing access to sensitive data and resources is paramount. Traditional authentication methods often require users to share their long-term credentials with third-party applications, posing significant security risks. Enter OAuth 2.0, a powerful authorization framework designed to address these concerns by allowing users to grant third-party websites or applications access to their protected resources without revealing their long-term credentials or identity. OAuth 2.0 introduces an innovative authorization layer that separates the role of the client (the application requesting access) from the resource owner (the user). In this framework, the client requests access to resources controlled by the resource owner and hosted by the resource server. Instead of using the resource owner’s credentials, the client is issued an Access Token— a string that defines the specific scope, lifetime, and other access attributes. This token is issued by an authorization server with the user’s approval, enabling the client to access the protected resources on the resource server securely. Platforms like Auth0 further enhance this process by generating access tokens in JSON Web Token (JWT) format for API authorization scenarios. The permissions associated with these access tokens, known as scopes, define the level of access granted to the application. When an application authenticates with Auth0, it specifies the desired scopes. If these scopes are authorized by the user, the access token will represent these authorized permissions, ensuring secure and granular access control. In this blog post, we will discuss how configuring identity providers on Confluent Cloud allows you to manage application access without depending on user accounts. This section covers various aspects of configuring and managing identity providers for OAuth/OIDC. Pros and Cons of Using OAuth Pros Security: Reduces the risk associated with sharing long-term credentials. Limits the access granted to third-party applications, minimizing potential damage from compromised tokens. Granular Access Control: Users can grant specific permissions (scopes) to third-party applications. Tokens can have limited lifetimes and scopes, offering fine-grained control over access. User Experience: Simplifies the process of granting access to third-party applications. Users authenticate with a trusted authorization server, improving confidence in the security of their credentials. Cons Complexity: Setting up OAuth can be complex, especially if you’re not familiar with it. The configuration involves multiple components such as authorization servers, scopes, tokens, and client credentials, which can be challenging to manage without prior experience. Dependency: OAuth relies on an identity provider for authentication. This dependency introduces additional points of failure. If the identity provider experiences downtime or issues, it can affect the entire authentication flow. This identity provider could be any service, not necessarily Okta, and the reliance on this external service adds a layer of dependency that needs to be managed carefully. When to Use OAuth When you require secure, token-based authentication to manage access to resources. If you are using Confluent Cloud in an enterprise setting where centralized identity management is important, and you need to ensure that access control is streamlined and consistent across multiple systems and applications. When integrating with systems that support OAuth for seamless interoperability and access control. Let’s Dive into Configuring Okta! Step 1 : Application integration in Okta By setting up an application in Okta, you configure the authentication methods, such as OpenID Connect (OIDC), that will be used to secure the connection to your Confluent Cloud cluster. This ensures that only authorized clients can access the resources.The setup process in Okta generates a Client ID and Client Secret, which are essential for authenticating your application with Confluent Cloud. These credentials are used to request access tokens, which are then used to access Confluent Cloud resources securely. How to Set Up Application Integration in Okta? Log in to Okta Admin Console Access your Okta Admin Console at https://{yourOktaDomain}/admin. Navigate to Applications: From the left-hand menu, click on “Applications” and then select “Applications” again. Create a New Application Integration: Click on “Create App Integration.” Choose Application Type: Select “OIDC - OpenID Connect” for applications using OAuth 2.0 or OpenID Connect, then click “Next.” Configure Application Settings: Enter a descriptive name for your application (e.g., Kafka Client) and choose “Client Credentials” as the sign-on method. Set Additional Options: Ensure “Client Credentials Grant” is selected. Configure or leave “Redirect URIs” and “Logout Redirect URIs” as needed. Complete the Setup: Click “Save” to finalize the configuration. Obtain Client Credentials: After saving, go to the application’s “General” tab to find and record the Client ID and Client Secret. Step 2: Configure the Authorization Server An authorization server is a key component in the OAuth 2.0 and OpenID Connect (OIDC) frameworks. Its primary function is to issue tokens that control access to protected resources and enable user authentication. By providing tokens like access tokens and ID tokens, the authorization server manages and secures access to various services. It enforces access policies to determine which resources can be accessed and under what conditions. Each authorization server has a unique issuer URI and a specific signing key to ensure the security and integrity of the tokens it issues. This setup helps maintain clear security boundaries and enhances overall protection. In Okta, configuring the authorization server allows you to: Create Access Policies: Set rules to define who can access which resources and under what conditions. Create Rules for Each Access Policy: Specify detailed rules that determine how access policies are enforced. Create Scopes: Define the permissions that applications can request, specifying the level of access they are granted. Create Claims: Specify the attributes included in tokens, such as user roles or email addresses, to provide essential information for authorization decisions. By configuring these elements, you ensure that tokens are aligned with your security policies and access requirements, allowing for effective control over resource access. Integrating Okta with Confluent Cloud: A Configuration Walkthrough Steps to Configure an Okta Identity Provider in Confluent Cloud To configure Confluent Cloud we have to first register the IdP. Go to Accounts & access from the menu in the top right, and select the Identity providers tab. Select the Add Identity Providers button and choose Okta, then press Next. In next screen enter the details for the okta : Name: Enter a meaningful name for your Okta identity provider. Description: Provide relevant information for managing this provider. Authorization Server: Enter the identifier for your Okta authorization server. The default is “default,” but this can be modified if needed. Domain: Enter the domain for your Okta instance. The default is {yourDomain}.okta.com. Replace {yourDomain} with your actual Okta domain name. OIDC Discovery URL: Click to import metadata required for configuring your OIDC provider. This action will populate the JWKS URI and Issuer URI fields automatically. JWKS URI: Enter the URI for the JSON Web Key Set (JWKS). Example: https://mycompany.okta.com/oauth2/default/v1/keys Issuer URI: Enter the issuer URI for your Okta identity provider. Example: https://mycompany.okta.com/oauth2/default This creates the provider, but we still have to configure identity pools. Do this by clicking the identity provider link.From this screen, we can create a new identity pool by pressing the Add pool button. Configure your identity pool and access policy. An identity pool is a group of external identities that are assigned a certain level of access based on policy. For details, see Use Identity Pools with Your OAuth/OIDC Identity Provider on Confluent Cloud. In the example below, we are assigning the Cluster Admin role to the identity pool pool-mPqE. This means that users accessing this cluster through the pool will have full Admin permissions and will be able to create, delete, and edit any resources. Configuring Your Kafka Client Set Client ID and Client Secret Use the Client ID and Client Secret from Okta to configure your Kafka client. Client Configuration in Kafka Update your Kafka client configuration to include these settings: properties 1 2 3 4 5 6 7 8 9 10 11 12 bootstrap.servers= security.protocol=SASL_SSL sasl.mechanism=OAUTHBEARER sasl.oauthbearer.token.endpoint.url=https://{yourOktaDomain}/oauth2/default/v1/token sasl.jaas.config= \ org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule required \ clientId='' \ clientSecret='' \ scope='openid' \ extension_logicalCluster='' \ extension_identityPoolId=''; Request a JSON Web Token (JWT) Authenticate using Client Credentials: Use the Client ID and Client Secret to request a JWT from Okta via the OAuth 2.0 Client Credentials Grant.The response will contain an access_token which is a JWT. 1 2 3 4 5 curl --request POST \ --url https://{yourOktaDomain}/oauth2/default/v1/token \ --header 'Content-Type: application/x-www-form-urlencoded' \ --data 'grant_type=client_credentials&client_id=&client_secret=&scope=openid' Example: Role-Based Testing Cluster Administrator Set up the Cluster Admin role for the cluster in Confluent Cloud. With this role, I am able to create and delete topics. Operator Set up the Operator role. This role allows you to view and describe topics but does not grant permissions to create or delete them. Breaking Down the OAuth 2.0 Flow Confluent OAuth uses the OAuth 2.0 protocol for authentication and authorization. OAuth is a widely-used standard that provides temporary access tokens to clients. These tokens allow clients to access and use Confluent Cloud resources and data on behalf of a user or application. Establish Trust Between Confluent and Your Identity Provider Add the Identity Provider: Ensure that the identity provider (e.g., Okta) is registered with Confluent Cloud. This usually involves providing some configuration details to Confluent Cloud. Define the Type of Identity Provider: Specify whether the identity provider is OAuth 2.0 or OIDC (OpenID Connect). Each provider might have specific requirements for integration. Create a Trust Relationship: This involves configuring Confluent Cloud to trust tokens issued by your identity provider. You might need to upload or specify the public keys or JWKS (JSON Web Key Set) URL from your identity provider. Add Claims for Authentication and Authorization: Define which claims from the JWT will be used for authentication and authorization. Common claims include sub (subject), aud (audience), and custom claims like user roles or groups. Configure Your Identity Pool and Access Policy Identity Pool: Create an identity pool in Confluent Cloud, which groups external identities and assigns them access based on policies. You might need to configure mappings to ensure the correct access levels. Access Policy: Define what resources the identities in the pool can access and what actions they can perform. Configure Clients Client ID and Client Secret: Obtain these from your identity provider. They are used to authenticate the client (Kafka producer/consumer) with the identity provider. Client Credentials Grant: The client uses the Client ID and Client Secret to request an access token (JWT) from the identity provider. Producer/Consumer Configuration Example: Use the following Kafka client settings for OAuth 2.0 authentication: 1 2 3 4 5 6 7 8 9 10 11 12 13 log4j.logger.org.apache.kafka=TRACE bootstrap.servers=pkc-p11xm.us-east-1.aws.confluent.cloud:9092 security.protocol=SASL_SSL sasl.oauthbearer.token.endpoint.url=https://trial-6662742.okta.com/oauth2/aush040p2xDZzZHcu697/v1/token sasl.login.callback.handler.class=org.apache.kafka.common.security.oauthbearer.secured.OAuthBearerLoginCallbackHandler sasl.mechanism=OAUTHBEARER sasl.jaas.config= \ org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule required \ clientId='0oah03x6a2AjiQJZl697' \ scope='api_scope' \ clientSecret='QSG_xMfvaQ-Vw_i_3DzsfaHYg6K551p-Mfo7vNyMEcLDuY8E35ZUWIIivR4ZwgoQ' \ extension_logicalCluster='lkc-37vn0o' \ extension_identityPoolId='pool-mPqE'; \ Validate the Token Confluent Cloud Token Validation: Confluent Cloud validates the JWT received from the Kafka client. It checks the token against the trusted JWKS and verifies the claims to map to the appropriate authorization policy. JSON Web Token (JWT) Example: 1 2 3 4 5 6 7 8 9 10 11 12 13 { "ver": 1, "jti": "AT.8p0wrTPUIm8yBHqgiKDrnJQ_32_MNc_FlkuqOjq8VCQ", "iss": "https://trial-6662742.okta.com/oauth2/aush040p2xDZzZHcu697", "aud": "confluent", "iat": 1721739387, "exp": 1721742987, "cid": "0oah03x6a2AjiQJZl697", "scp": [ "api_scope" ], "sub": "0oah03x6a2AjiQJZl697" } The JWT includes claims such as sub for the user ID, aud for the audience, and groups for any group memberships, which Confluent Cloud uses to determine access rights. Conclusion OAuth 2.0 and Okta together offer a robust framework for managing secure and efficient access to your resources. By integrating Okta as your identity provider, you simplify the authentication process and enhance security, allowing you to control access through OAuth tokens and scopes. Configuring Okta with Confluent Cloud and your Kafka client ensures that your systems are protected from unauthorized access while maintaining smooth and manageable workflows. Embracing this setup not only strengthens your security measures but also optimizes the overall efficiency of your access management, providing a seamless experience for both administrators and users. References https://developer.okta.com/docs/guides/authorization/ https://help.okta.com/en-us/content/topics/security/api_access.htm https://confluent/idp https://docs.confluent.io/cloud/current/security/authenticate/workload-identities/identity-providers/oauth/overview.html#oauth-overview --- # Real Time Data Architecture In Retail URL: https://platformatory.io/blog/Real-time-data-architecture-in-retail/ Published: 2024-07-23 Authors: Ashwin Venkatesan Categories: Real-time, Kafka, Data Engineering, Retail Introduction Retail industry is one of the fastest growing sector in terms of data and analytics. According to the recent study from Fortune Business Insights, the global retail analytics market size was valued at USD 7.56 billion in 2023 and is projected to grow to USD 31.08 billion by 2032, exhibiting a CAGR of 17.2%. Although, a lot of money is pumped into analytics only a few selected companies like Walmart, Amazon etc. hold the majority of the market share. The reason being they are equipped to make many important decisions based on an ever-growing supply of real-time and historical data while most of their competitors still use very basic tools that are far better able at tracking where they’ve been than where they should be going. During the pandemic, McKinsey estimates, the 25 top-performing retailers — most of whom are digital leaders — were 83% more profitable than laggards and took home more than 90% of the sector’s gains in market capitalization. Why Real time data is important in Retail? Retail customers are generally fickle, and their preferences can change in an instant. Each moment is a point in time when a customer interacts with a brand to get what they want immediately and in context. Real-time data allows retailers to respond swiftly to changes in customer behaviour, offering personalized experiences that can significantly enhance customer satisfaction. For example, Amazon’s recommendation engine, accounts for an impressive 35% of their total revenue. Amazon has achieved a substantial increase in ROI through customized homepage displays, advanced analysis of browsing and purchase history tied to the customer’s Amazon account, and strategic email marketing campaigns, By leveraging real-time analytics, companies can optimize inventory management, reduce stockouts, and improve the efficiency of supply chain operations. This not only boosts sales and reduce Customer Acquisition Costs (CAC) but also helps in retaining customer loyalty. A study by IDC highlights that retailers harnessing real-time data analytics can slash their inventory costs by up to 15% and increase their sales by up to 10%. Providing a seamless and personalized shopping experience across channels in real-time contributes to increasing Customer Lifetime Value (CLV). Maslow’s Hierarchy of data management in Retail Top 5 Foundational Capabilities for Managing Data in Retail Leading Up to Direct Impact on Customer Experience 1. Inventory Visibility Achieving end-to-end supply chain visibility involves having real-time insights into the entire journey of products. According to CSCMP’s 2023 State of Logistics Report, in 2022, the U.S. Business Logistics Cost went up as much as 19.6%, the largest increase to date, of which 52% was due to an increase in inventory carrying costs. In this economic climate, stocking shelves inadequately, letting down consumers and misjudging demand can lead to catastrophic consequences Inventory visibility is crucial for managing stock levels effectively and ensuring that products are available when customers need them. Logging in orders and sales data through various tools allows retailers to react quicker based on the data. This leads to optimized inventory levels, improved customer satisfaction, and reduced costs associated with excess inventory, stockouts, and rush shipments. 2. Omnichannel Integration Shoppers now have more flexibility and can chose different formats for both shopping and fulfilment. Some shoppers tend to go online in search of information, and then actually conclude the transaction in a physical store. Others might go to a store or a showroom to do research, and then they go online to make their purchase. Retailers today have to understand and enable this flexibility and seamless movement across channels Therefore, a seamless data integration across multiple operational channels, such as online stores, physical shops, and mobile apps is paramount. By synchronizing data across all channels, retailers can provide a consistent and unified shopping experience for customers. This integration helps in managing inventory, customer preferences, and sales data more effectively, leading to better customer experiences. 3. Dynamic Pricing Dynamic pricing makes sense for staying relevant in retail where competition is ever-growing because it allows retailers to adjust prices in real-time based on a variety of factors such as customer buying behaviour, seasonal trends, competitor pricing, and product performance. This flexibility ensures that prices remain competitive and appealing to customers, helping to maximize sales and profitability. In a market where consumer preferences and competitive landscapes can change rapidly, dynamic pricing helps retailers react swiftly to these changes, offering the right price at the right time to attract and retain customers. 4. Fulfillment Speed Fulfillment speed is a critical factor in customer satisfaction. Retailers can improve fulfillment speed through dynamic routing based on weather, traffic conditions, and automation. Real-time tracking of orders ensures that customers are informed about the status of their purchases, leading to a better shopping experience. Faster fulfillment also reduces the likelihood of abandoned carts and enhances customer loyalty. Accurately forecasting demand and supply enables retailers to manage inventory more efficiently, ensuring that popular products are stocked and ready for quick dispatch. Effective demand and supply forecasting also allows for better workforce planning and allocation of resources, leading to faster order processing and quicker delivery times. 5. Deep Personalization Deep personalization is the ultimate goal in retail because it directly impacts customer satisfaction, loyalty, and ultimately, the bottom line. By providing highly personalized experiences, retailers can create deeper emotional connections with their customers, making them feel valued and understood. The ability to dynamically adjust content, offers, and recommendations based on real-time data ensures that customers receive the most relevant information at any given moment, which is critical for maintaining customer engagement. Utilizing sophisticated algorithms and machine learning models helps in accurately predicting customer preferences and behaviors, leading to more effective personalization strategies. Barebone Streaming Architecture in Retail In today’s fast-paced retail environment, leveraging real-time data architecture is crucial for staying ahead of the competition. Here are the key components of real-time data architecture in retail: Data Sources The first step in building a real-time data architecture is identifying and integrating various data sources. These can include point-of-sale (POS) systems, e-commerce platforms (clickstream etc), social media feeds, CDP etc. Capabilities to collect data across both physical and digital stores is an important requirement. Event Bus A centralized event bus is essential for managing the flow of data between different systems and components. It serves as a backbone for real-time data pipelines, ensuring efficient data transfer and integration. Apache Kafka is an ideal choice for this purpose. It allows for high-throughput, low-latency data streaming and can handle large volumes of events in real-time. This capability is particularly critical for retailers who need to quickly respond to changes in customer behaviour, manage inventory in real-time, and provide dynamic pricing updates. Kafka also supports a wide range of connectors for external systems enabling effective data ingress and egress capabilities. Stream Processing Layer Real-time data processing is crucial for extracting actionable insights. Technologies like Apache Flink, Kafka Streams, and Storm enable continuous data processing. Ingested data can be transformed, filtered and aggregated on the fly for downstream processing services. Data can be enriched with historical information through joins which might be relevant for further processing. Additionally, Real time predictions can be captured for the processed data points and stored in a database for retrieval. Real-time predictions allow for instant decision-making based on the most recent data realising maximum data impact value. Decision-making Microservices Intelligent decision-making microservices are the brain of the real-time data architecture. These microservices use the processed data to make real-time decisions that can significantly impact retail operations. For example, a pricing microservice can dynamically adjust product prices based on current demand, competitor pricing, and inventory levels. Similarly, a recommendation microservice can provide personalized product suggestions to customers based on their browsing and purchase history. A decision-making microservice can range from a simple rule based service to deep learning models. These microservices are designed to learn and improve over time, becoming increasingly intelligent and effective through the usage of real time features. A maturity lifecycle for a microservice can include the following steps, CEP/Rule-driven Supervised Learning models Ensemble models Deep Learning models Data Analytics and Visualization The final component is data analytics and visualization, which provides a centralized dashboard for analyzing customer behavior in real-time. This dashboard allows retailers to monitor key performance indicators (KPIs), track trends, and gain insights into customer preferences and market dynamics. Retailers can also use these tools to track customer engagement across various channels, allowing them to tailor marketing strategies and improve customer experiences. Real-time visualization tools help in making data-driven decisions quickly and effectively. Example implementation Let’s see an example on how to implement the mentioned Real time data architecture. Link for the the Github repository. Objective: Based on the Shopify inventory changes and clickstream data dynamically predict the price and the sell through date for the available products in real time. Prerequisites: Shopify Store Docker ngrok Details: Kafka Broker will be used as the Event bus for the inventory and clickstream data Kafka connect will be used to source the data from the data sources and get the predictions from the microservices KSQL will be used to perform ETL on the source data for downstream predictions Flask APIs will be used to expose endpoints to talk to prediction microservices Setup the infrastructure: We will run all the required components as docker containers locally. Following is the docker-compose.yaml for the required services. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 --- version: "2" services: broker: image: confluentinc/cp-kafka:7.5.0 hostname: broker container_name: broker ports: - "9092:9092" - "9101:9101" environment: KAFKA_NODE_ID: 1 KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: "CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT" KAFKA_ADVERTISED_LISTENERS: "PLAINTEXT://broker:29092,PLAINTEXT_HOST://localhost:9092" #KAFKA_METRIC_REPORTERS: io.confluent.metrics.reporter.ConfluentMetricsReporter #KAFKA_CONFLUENT_METRICS_REPORTER_BOOTSTRAP_SERVERS: 'broker:9092' KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1 KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0 KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1 KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1 KAFKA_JMX_PORT: 9101 KAFKA_JMX_HOSTNAME: localhost KAFKA_PROCESS_ROLES: "broker,controller" KAFKA_CONTROLLER_QUORUM_VOTERS: "1@broker:29093" KAFKA_LISTENERS: "PLAINTEXT://broker:29092,CONTROLLER://broker:29093,PLAINTEXT_HOST://0.0.0.0:9092" KAFKA_INTER_BROKER_LISTENER_NAME: "PLAINTEXT" KAFKA_CONTROLLER_LISTENER_NAMES: "CONTROLLER" KAFKA_LOG_DIRS: "/tmp/kraft-combined-logs" # Replace CLUSTER_ID with a unique base64 UUID using "bin/kafka-storage.sh random-uuid" # See https://docs.confluent.io/kafka/operations-tools/kafka-tools.html#kafka-storage-sh CLUSTER_ID: "41PmKs1mQiGJK0U_Ul45OA" connect: build: context: . dockerfile: Dockerfile hostname: connect container_name: connect ports: - 8083:8083 - 8000:8000 depends_on: - broker - api environment: CONNECT_BOOTSTRAP_SERVERS: "broker:29092" CONNECT_REST_ADVERTISED_HOST_NAME: connect CONNECT_GROUP_ID: compose-connect-group CONNECT_CONFIG_STORAGE_TOPIC: docker-connect-configs CONNECT_CONFIG_STORAGE_REPLICATION_FACTOR: 1 CONNECT_OFFSET_FLUSH_INTERVAL_MS: 10000 CONNECT_OFFSET_STORAGE_TOPIC: docker-connect-offsets CONNECT_OFFSET_STORAGE_REPLICATION_FACTOR: 1 CONNECT_STATUS_STORAGE_TOPIC: docker-connect-status CONNECT_STATUS_STORAGE_REPLICATION_FACTOR: 1 CONNECT_KEY_CONVERTER: org.apache.kafka.connect.storage.StringConverter CONNECT_VALUE_CONVERTER: org.apache.kafka.connect.json.JsonConverter # CLASSPATH required due to CC-2422 CLASSPATH: /usr/share/java/monitoring-interceptors/monitoring-interceptors-7.5.0.jar CONNECT_PRODUCER_INTERCEPTOR_CLASSES: "io.confluent.monitoring.clients.interceptor.MonitoringProducerInterceptor" CONNECT_CONSUMER_INTERCEPTOR_CLASSES: "io.confluent.monitoring.clients.interceptor.MonitoringConsumerInterceptor" CONNECT_PLUGIN_PATH: "/usr/share/java,/usr/share/confluent-hub-components" CONNECT_LOG4J_LOGGERS: org.apache.zookeeper=ERROR,org.I0Itec.zkclient=ERROR,org.reflections=ERROR volumes: - ./retail_clickstream_schema.avro:/home/appuser/retail_clickstream_schema.avro ksqldb-server: image: confluentinc/cp-ksqldb-server:7.5.0 hostname: ksqldb-server container_name: ksqldb-server depends_on: - broker - connect ports: - "8088:8088" environment: KSQL_CONFIG_DIR: "/etc/ksql" KSQL_BOOTSTRAP_SERVERS: "broker:29092" KSQL_HOST_NAME: ksqldb-server KSQL_LISTENERS: "http://0.0.0.0:8088" KSQL_CACHE_MAX_BYTES_BUFFERING: 0 KSQL_PRODUCER_INTERCEPTOR_CLASSES: "io.confluent.monitoring.clients.interceptor.MonitoringProducerInterceptor" KSQL_CONSUMER_INTERCEPTOR_CLASSES: "io.confluent.monitoring.clients.interceptor.MonitoringConsumerInterceptor" KSQL_KSQL_CONNECT_URL: "http://connect:8083" KSQL_KSQL_LOGGING_PROCESSING_TOPIC_REPLICATION_FACTOR: 1 KSQL_KSQL_LOGGING_PROCESSING_TOPIC_AUTO_CREATE: "true" KSQL_KSQL_LOGGING_PROCESSING_STREAM_AUTO_CREATE: "true" # KSQL_KSQL_QUERIES_FILE: /home/appuser/ksql_queries.sql volumes: - ./ksql_queries.sql:/home/appuser/ksql_queries.sql ksqldb-cli: image: confluentinc/cp-ksqldb-cli:7.5.0 container_name: ksqldb-cli depends_on: - broker - connect - ksqldb-server entrypoint: /bin/sh tty: true api: build: context: ./api dockerfile: Dockerfile hostname: api container_name: api ports: - 5000:5000 Create a ShopifyWebhookConnector to fetch the inventory changes from Shopify. Since the setup is local, we need to expose the endpoint publicly using ngrok so that Shopify can send data on updates in the Store. 1 export NGROK_PUBLIC_URL=`curl -s localhost:4040/api/tunnels | jq -r '.tunnels[0].public_url'` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 { "name": "$CONNECTOR_NAME", "config": { "connector.class": "com.platformatory.kafka.connect.ShopifyWebhookConnector", "tasks.max": 1, "topic.default": "webhook", "topic.header": "X-Shopify-Topic", "topic.prefix": "plf_", "key.json.path": "$.id", "schema.infer": false, "validator.class": "com.platformatory.kafka.connect.ShopifyRequestValidator", "port": 8000, "shopify.access.token": "$SHOPIFY_ACCESS_TOKEN", "shopify.webhook.create": true, "shopify.store.name": "$SHOPIFY_STORE_NAME", "shopify.webhook.topics": "products/update", "shopify.apisecret": "$SHOPIFY_API_SECRET", "shopify.connector.hostname": "$NGROK_PUBLIC_URL" } } We will use mock data for the clickstream data. This mock data will be generated using the DatagenConnector with a pre-defined schema type. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 { "name": "$CONNECTOR_NAME", "config": { "connector.class": "io.confluent.kafka.connect.datagen.DatagenConnector", "tasks.max": "1", "kafka.topic": "shopify_clickstream", "schema.filename": "/home/appuser/retail_clickstream_schema.avro", "schema.keyfield": "activity", "topic.creation.default.partitions": 6, "topic.creation.default.replication.factor": 1, "key.converter": "org.apache.kafka.connect.storage.StringConverter", "value.converter": "org.apache.kafka.connect.json.JsonConverter", "value.converter.schemas.enable": "false" } } Load both the shopify inventory data and clickstream data as STREAMS in KSQL 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 CREATE OR REPLACE STREAM PRODUCTS_UPDATE_STREAM (PAYLOAD STRUCT< id BIGINT, created_at STRING, inventory_management STRING, title STRING, vendor STRING, variants Array< Struct< id BIGINT, created_at STRING, title STRING, inventory_item_id BIGINT, inventory_quantity BIGINT, old_inventory_quantity BIGINT, sku STRING, price STRING, product_id BIGINT > > > ) WITH (KAFKA_TOPIC='plf_products_update', KEY_FORMAT='KAFKA', VALUE_FORMAT='JSON'); CREATE OR REPLACE STREAM CLICKSTREAM_STREAM ( time STRING, user_id BIGINT, product_variant_id BIGINT, activity STRING, ip STRING ) WITH (KAFKA_TOPIC='shopify_clickstream', KEY_FORMAT='KAFKA', VALUE_FORMAT='JSON'); Create a transformed inventory stream called PRODUCTS_UPDATES with only with the required information 1 2 3 4 5 6 7 8 9 10 CREATE OR REPLACE STREAM PRODUCTS_UPDATES WITH (KAFKA_TOPIC='ksql_product_updates', PARTITIONS=6, REPLICAS=1) AS SELECT PAYLOAD->id id, PAYLOAD->created_at created_at, PAYLOAD->inventory_management inventory_management, PAYLOAD->title title, PAYLOAD->vendor vendor, EXPLODE(PAYLOAD->variants) variant FROM PRODUCTS_UPDATE_STREAM EMIT CHANGES; For every product variant in clickstream, aggregate the number of product views and create a KTable 1 2 3 4 5 6 7 8 9 10 CREATE OR REPLACE TABLE CLICKSTREAM_ACTIVITY WITH (KAFKA_TOPIC='ksql_clickstream_activity', PARTITIONS=6, REPLICAS=1, KEY_FORMAT='JSON') AS SELECT product_variant_id product_variant_id, COUNT(activity) activity_count FROM CLICKSTREAM_STREAM WHERE activity='contentView' GROUP BY product_variant_id EMIT CHANGES; Join the aggregated clickstream data and inventory data for each product variant and write to a output topic 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 CREATE OR REPLACE STREAM PRODUCT_CLICKSTREAM WITH (KAFKA_TOPIC='ksql_product_clickstream', PARTITIONS=6, REPLICAS=1) AS SELECT p.id product_id, p.created_at product_created_at, p.inventory_management inventory_management, p.title product_title, p.vendor product_vendor, p.variant->created_at variant_created_at, p.variant->inventory_item_id variant_inventory_item_id, p.variant->old_inventory_quantity old_inventory_quantity, p.variant->inventory_quantity inventory_quantity, p.variant->sku variant_sku, p.variant->price price, c.product_variant_id variant_id, c.activity_count activity_count FROM PRODUCTS_UPDATES p INNER JOIN CLICKSTREAM_ACTIVITY c ON ((p.variant->id = c.product_variant_id)) EMIT CHANGES; Sample microservices which returns predictions for price and sell through date will be exposed via Flask APIs. Microservices are just dummy functions for this example implementation. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 from flask import Flask,request,jsonify from datetime import timedelta,datetime,date from random import randrange import ast app = Flask(__name__) @app.route('/') def index(): return 'Index Page' @app.route('/user', methods=["POST"]) def get_user(): data = request.get_json() username = data['username'] password = data['password'] print({username, password }) return {"username":username, password: password} def predict_sell_through(inventory_data): average_daily_sales = inventory_data['total_sales'] / inventory_data['total_days'] days_until_sell_through = inventory_data['quantity_on_hand'] / average_daily_sales sell_through_date = datetime.now() + timedelta(days=days_until_sell_through) inventory_doh = inventory_data['quantity_on_hand'] / average_daily_sales return sell_through_date, inventory_doh @app.route('/stores//inventory_forecast/predict', methods=["POST"]) def show_post(store_name): try: inventory_data = request.json if not inventory_data: return jsonify({'error': 'No data provided'}), 400 sell_through_date, inventory_doh = predict_sell_through(inventory_data) print(sell_through_date, inventory_doh, inventory_data) return jsonify({ 'sell_through_date': sell_through_date.strftime('%Y-%m-%d'), 'inventory_doh': int(inventory_doh) }) except Exception as e: return jsonify({"error": str(e)}) @app.route('/dynamic-pricing', methods=['POST']) def dynamic_pricing(): try: data = request.get_json()[0] print(data) if data["ACTIVITY_COUNT"]>3: data["dynamic_price"] = float(data["PRICE"])*1.1 else: data["dynamic_price"] = float(data["PRICE"])*1.01 return data, 200 except Exception as e: # Handle any exceptions print(f"Error processing request: {str(e)}") return jsonify({'error': 'An error occurred'}), 500 @app.route('/sell-through', methods=['POST']) def sell_through_date(): try: data = request.get_json()[0] print(data) # date + random days (5-10) data["sell_through_date"] = datetime.now() + timedelta(days=randrange(10)) return data, 200 except Exception as e: # Handle any exceptions print(f"Error processing request: {str(e)}") return jsonify({'error': 'An error occurred'}), 500 if __name__ == "__main__": app.run(host='0.0.0.0', port=5000) # curl -X POST http://localhost:5000/stores/acme/inventory_forecast/predict -H 'Content-Type:application/json' -d '{"total_sales":453,"total_days":32,"quantity_on_hand":98,"current_date":"2024-04-10T15:17"}' Create 2 HttpSinkConnector which will get the price and sell through predictions for each enriched data from the KSQL output topic and write it to respective success topics. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 ## Dynamic pricing { "name": "$CONNECTOR_NAME", "config": { "connector.class": "io.confluent.connect.http.HttpSinkConnector", "tasks.max":1, "http.api.url":"http://api:5000/dynamic-pricing", "headers":"Content-Type:application/json|Accept:application/json", "request.body.format": "json", "reporter.result.topic.replication.factor":1, "reporter.error.topic.replication.factor":1, "reporter.bootstrap.servers": "broker:29092", "confluent.topic.bootstrap.servers": "broker:29092", "confluent.topic.replication.factor": "1", "topics": "ksql_product_clickstream", "key.converter": "org.apache.kafka.connect.storage.StringConverter", "value.converter": "org.apache.kafka.connect.json.JsonConverter", "value.converter.schemas.enable": "false" } } ## Sell through date { "name": "$CONNECTOR_NAME", "config": { "connector.class": "io.confluent.connect.http.HttpSinkConnector", "tasks.max":1, "http.api.url":"http://api:5000/sell-through", "headers":"Content-Type:application/json|Accept:application/json", "request.body.format": "json", "reporter.result.topic.replication.factor":1, "reporter.error.topic.replication.factor":1, "reporter.bootstrap.servers": "broker:29092", "confluent.topic.bootstrap.servers": "broker:29092", "confluent.topic.replication.factor": "1", "topics": "ksql_product_clickstream", "key.converter": "org.apache.kafka.connect.storage.StringConverter", "value.converter": "org.apache.kafka.connect.json.JsonConverter", "value.converter.schemas.enable": "false" } } In this example, we were able to demonstrate a sample real time data pipeline for a retail use case where we are predicting price and sell through date based on product inventory and clickstream activity. Conclusion The implementation of a real-time data architecture in retail is essential for gaining a competitive edge in today’s fast-paced market. By leveraging real-time data, retailers can enhance customer satisfaction through dynamic routing, accurate demand forecasting, and deep personalization. As the retail landscape continues to evolve, investing in real-time data capabilities will be crucial for optimizing operations, improving customer experiences, and driving business growth. --- # Migrating Zookeeper to Kraft URL: https://platformatory.io/blog/Migrating-Zookeeper-to-kraft/ Published: 2024-07-22 Authors: Shivaprakash Akki Categories: Kafka, Migration, KRaft, Kafka Operations Introduction In its evolution, Kafka has recently shifted away from relying on ZooKeeper to manage its essential metadata and now embraces a quorum-based controller using Kafka Raft, or KRaft (pronounced ‘craft’), which has been generally available since Confluent Platform version 7.4. Apache Kafka has traditionally entrusted ZooKeeper with crucial tasks such as storing metadata, managing brokers, controlling topics, and overseeing cluster configurations. Initially, this centralized approach with ZooKeeper was ideal for ensuring robust distributed coordination and reliable leader election mechanisms. However, the complexity of maintaining ZooKeeper alongside a Kafka cluster has become evident over time. Moreover, ZooKeeper’s limitations have emerged as a bottleneck, restricting the scalability of Kafka clusters by limiting the number of partitions a single broker can effectively manage. Recognizing these challenges and seeking to streamline Kafka’s architecture, the Kafka community introduced KIP-500. This initiative aims to phase out ZooKeeper and introduce a more efficient metadata quorum solution. This blog post is dedicated to guiding you through the transition from ZooKeeper to KRaft. We will provide a step-by-step roadmap for migrating your Kafka deployment to KRaft. Why Bye to ZooKeeper ? ZooKeeper data is replicated across a number of nodes forming an ensemble, using the ZooKeeper Atomic Broadcast (ZAB) protocol to ensure data consistency across all nodes. However, integrating ZooKeeper with Kafka involves managing a separate distributed system alongside Kafka itself, which introduces additional complexities in deployment, management, and troubleshooting. Moreover, ZooKeeper introduces scalability bottlenecks that limit the number of topics and partitions supported within a Kafka cluster. For example, during controller failover events, the newly elected controller must retrieve metadata from ZooKeeper, including details for all topics, which can impact performance. Additionally, any metadata updates require propagation to other brokers via RPCs, and as the number of partitions increases, the propagation time grows, potentially slowing down the system. In contrast, other distributed systems like MongoDB, Cassandra, and Elasticsearch handle metadata management internally, eliminating the need for external tools like ZooKeeper. This streamlined approach significantly simplifies deployment and operational management—imagine handling just one distributed system instead of two! Furthermore, internal metadata management enhances scalability and efficiency, optimizing operations and providing stronger guarantees for Kafka’s functionality. Hello from KRaft! To address challenges with ZooKeeper, the Kafka community introduced KRaft, a new way to handle metadata directly within Kafka itself. Unlike ZooKeeper, which required managing a separate system alongside Kafka, KRaft integrates metadata management into Kafka using an event-driven approach. KRaft uses a quorum-based controller with an event-driven implementation of the Raft protocol. This controller manages an event log stored in a special topic named “__cluster_metadata.” Unlike regular topics, data in “__cluster_metadata” is written synchronously to disk, ensuring reliability required by Raft. Advantages of KRaft Simplicity: KRaft streamlines Kafka’s architecture by eliminating the need for a separate coordination service like ZooKeeper. Users and operators only need to manage one system, and KRaft uses the same configuration, failure handling, and security mechanisms as Kafka’s data plane, making it easier to learn and operate. Scalability: KRaft enhances Kafka’s scalability by reducing the load on the metadata store. In KRaft mode, only a subset of brokers, known as the controller quorum, handles metadata. This setup minimizes connections and requests to the metadata store, enabling Kafka to support more brokers and topics without impacting performance. Availability: KRaft improves Kafka’s availability by allowing the system to handle partial failures. Only a quorum of controllers is needed to process requests, so if some controllers are down or disconnected, the remaining ones can still maintain cluster operations. This makes Kafka more resilient to network issues and data center failures. Simplified Deployment and Management: With KRaft, you no longer need to manage a separate ZooKeeper cluster, reducing operational complexity and costs. Kafka users can continue using existing tools and APIs, such as the Admin API and kafka-reassign-partitions tool, for managing their clusters. Increased Security: KRaft supports encryption and authentication for client-server communication using SSL/TLS or SASL, ensuring that Kafka metadata is protected from unauthorized access or tampering. By adopting KRaft, Kafka enhances its scalability, simplifies operations, and integrates metadata management directly into its architecture, offering a more efficient alternative to ZooKeeper. How to migrate from ZooKeeper to KRaft While KRaft has been production-ready for several releases now, with continuous feature enhancements, the majority of existing Kafka clusters still rely on ZooKeeper. However, there’s growing interest among users to migrate to KRaft to overcome the limitations associated with ZooKeeper, as discussed earlier. Moreover, ZooKeeper will be deprecated within the Kafka project, with support expected to be fully removed in an upcoming release. This development underscores the urgency for Kafka users to plan and execute migrations from ZooKeeper to KRaft. Before beginning the migration process, our Kafka brokers are currently operating in ZooKeeper-mode and are connected to the ZooKeeper ensemble where metadata is stored. Let’s follow the steps below to migrate to KRaft. Step 1: Retrieve the cluster ID You must format storage for your Kafka cluster with the ID of the existing cluster. You can get this ID with the zookeeper-shell tool. Step 2: Configure a KRaft controller quorum Set up the KRaft controller quorum responsible for managing metadata in KRaft mode. Number of KRaft controller nodes should match the current ZooKeeper ensemble size. Migration does not support transitioning to “combined” mode nodes. Configure each KRaft controller node with connections to ZooKeeper. Add the flag zookeeper.metadata.migration.enable=true to signal the migration intent. Upon startup, KRaft controllers establish a quorum and elect a leader. Controllers enter a waiting state for Kafka brokers to register. 1 2 3 4 5 6 7 8 9 10 11 12 process.roles=controller node.id=3000 controller.quorum.voters=3000@localhost:9093 controller.listener.names=CONTROLLER listeners=CONTROLLER://:9093 # Enable the migration zookeeper.metadata.migration.enable=true # ZooKeeper client configuration zookeeper.connect=localhost:2181 # Enable migrations for cluster linking confluent.cluster.link.metadata.topic.enable=true # Other configuration entries Step 3: Format storage with the ID you saved previously Format storage on each node with the ID and the controller configuration file. Step 4: Start each controller Start each controller, specifying the configuration file with migration enabled. 1 ./bin/kafka-server-start.sh ./etc/kafka/kraft/controller.properties Step 5: Enable migration on the brokers Modify the Kafka broker configurations to include connection details for all nodes in the KRaft controller quorum. Enable the migration process using zookeeper.metadata.migration.enable=true in the broker configurations. Roll restart each Kafka broker one by one after updating its configuration. Upon restart, brokers will register with the KRaft controller quorum instead of ZooKeeper. This transition phase is referred to as the “hybrid phase,” where some brokers are still using ZooKeeper while the KRaft controller quorum starts managing metadata. The KRaft controller leader initiates the migration process by copying all metadata from ZooKeeper to the __cluster_metadata topic in Kafka. This ensures that all metadata (broker registrations, topic configurations, etc.) are replicated and synchronized across the KRaft quorum. Following is an example configuration file for a broker that is ready for the KRaft migration. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 broker.id=0 listeners=PLAINTEXT://:9092 advertised.listeners=PLAINTEXT://localhost:9092 listener.security.protocol.map=PLAINTEXT:PLAINTEXT,CONTROLLER:PLAINTEXT # Set the IBP inter.broker.protocol.version=3.6 # Enable the migration zookeeper.metadata.migration.enable=true # Cluster linking metadata topic enabled confluent.cluster.link.metadata.topic.enable=true # ZooKeeper client configuration zookeeper.connect=localhost:2181 # KRaft controller quorum configuration controller.quorum.voters=3000@localhost:9093 controller.listener.names=CONTROLLER Step 6: Migrate the brokers The KRaft controller operates in migration mode, sending RPCs like UpdateMetadata and LeaderAndIsr to ZooKeeper-mode brokers. Update broker configuration to switch from ZooKeeper-mode to KRaft-mode. Replace broker.id with node.id while maintaining the same identifier. Add process.roles=broker to indicate KRaft mode. Remove ZooKeeper configuration and any cluster linking entries from broker configuration. Update ACLs if necessary, especially changing the authorizer class. Restart the broker to apply the new configuration and complete the migration process. Following is an example of how a server.properties file for a migrated broker might look. Note that ZooKeeper-specific properties are commented out. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 process.roles=broker node.id=0 listeners=PLAINTEXT://:9092 advertised.listeners=PLAINTEXT://localhost:9092 listener.security.protocol.map=PLAINTEXT:PLAINTEXT,CONTROLLER:PLAINTEXT # Remove the IBP, KRaft uses "metadata.version" feature flag # inter.broker.protocol.version=3.6 # Remove the migration enabled flag # zookeeper.metadata.migration.enable=true # Remove the cluster linking metadata topic setting # confluent.cluster.link.metadata.topic.enable=true # Remove ZooKeeper client configuration # zookeeper.connect=localhost:2181 # Keep the KRaft controller quorum configuration controller.quorum.voters=3000@localhost:9093 controller.listener.names=CONTROLLER # If using ACLs, change the authorizer from AclAuthorizer used for ZooKeeper to the StandardAuthorizer used for KRaft. authorizer.class.name=kafka.security.authorizer Step 7: Take KRaft controllers out of migration mode Disable Migration: Comment out or remove the zookeeper.metadata.migration.enable=true property. This signals that the controllers are no longer in migration mode and are fully operational in KRaft mode. Remove ZooKeeper Configuration: Comment out or remove any ZooKeeper-specific configuration entries (zookeeper.connect=localhost:2181 in this example). Since KRaft mode no longer relies on ZooKeeper for metadata management, these entries are no longer needed. Example controller.properties File for KRaft Mode 1 2 3 4 5 6 7 8 9 10 11 process.roles=controller node.id=3000 controller.quorum.voters=3000@localhost:9093 controller.listener.names=CONTROLLER listeners=CONTROLLER://:9093 # Disable migration # zookeeper.metadata.migration.enable=true # Remove ZooKeeper client configuration. # zookeeper.connect=localhost:2181 Conclusion In this article, we’ve explored the role of ZooKeeper in Kafka and why Kafka has opted to transition to a quorum-based controller, KRaft. The Apache Kafka community has deprecated ZooKeeper for storing cluster metadata, with plans for complete removal in the upcoming version release. This signifies that users will need to transition towards KRaft-based clusters in the near future. Given the prevalence of ZooKeeper-based clusters currently in production, migrating to KRaft involves significant manual intervention, including configuration updates and rolling node restarts. --- # Unified access layer for Kafka resources: Part 2: Rule Based Routing Layer URL: https://platformatory.io/blog/unified-access-layer-part-2-rule-based-routing/ Published: 2024-07-13 Authors: Pavan Keshavamurthy, Raghavendran Nehru Categories: Kafka, Unified Access Layer, Platform Engineering, Infrastructure Introduction This is the Part 2 which is a follow up of Part 1 of the Unified Access Layer for Kafka Resources where we dive deep into the design and implementation of discovering Kafka resources via a rule based routing layer. Approach 1: Discover topics through a rule based routing layer Just to recap, here we are trying to build the pattern where a language specific SDK handles the Kafka resources discovery by talking to a catalog service. Let’s refer the overall architecture diagram: flowchart LR subgraph PRODUCERS["Producers"] P1("Producer 1") P2("Producer 2") P3("Producer 3") end subgraph CG1["Consumer Group 1"] C1("Consumer 1") end subgraph CG2["Consumer Group 2"] C2("Consumer 1") C3("Consumer 2") end subgraph CG3["Consumer Group 3"] C4("Consumer 1") C5("Consumer 2") end subgraph GW["Rule Based Routing Layer"] direction LR API["APIs (Kong)"] US["Upstream (Catalog Service)"] end subgraph K1["Kafka Cluster 1"] B1["Broker 1"] B2["Broker 2"] B3["Broker 3"] end subgraph K2["Kafka Cluster 2"] B4["Broker 1"] B5["Broker 2"] B6["Broker 3"] end P1 & P2 & P3 -- 1.GetInfo --> GW -- 2.Response --> P1 & P2 & P3 CG1 & CG2 & CG3 -- 1.GetInfo --> GW -- 2.Response --> CG1 & CG2 & CG3 P1 -- 3.Produces --> K1 P2 -- 3.Produces --> K2 P3 -- 3.Produces --> CC API --> US K1 -- 4.Consumes --> CG1 K2 -- 4.Consumes --> CG2 CC -- 4.Consumes --> CG3 %% Styling classDef kafkaStyle fill:#e0f7e9,stroke:#4caf50,stroke-width:2px; class K1,K2 kafkaStyle; Implementation Catalog Service This represents the catalog of all the Kafka resources that are needed by Clients (Producers and Consumers). This is implemented in the Kong API Gateway with A service that represents the Catalog Service upstream A route “/kafka-service-gw” on the service A custom plugin (or a pre-functions/post-functions plugin) that has a set of rules configured to retrieve the right Kafka bootstrap servers and topic information based on a set of query parameters (Channel, ServiceType, Organization). Clients can be either 1 call (ideally) or multiple calls to retrieve the information. Auth: all these calls are protected using Basic Auth The code can be found here Java Implementation for Kafka Producer and Consumer Kafka Producer Like we highlighted above, we need a custom consumer that can call the Catalog Service passing in the required information to locate the bootstrap servers and the topic. These will then be used to produce records (instead of the static configuration of the bootstrap servers and the topic). Here, we create a new ServiceLocatorProduder which is a facade around the KafkaProduder (routes all the calls to the internal Kafka Producer object). It first calls the Catalog Service passing the information needed and obtains the bootstrap servers and the kafka topic. As you can see below, any configuration change during the send will trigger an automatic refresh of the bootstrap servers and the topic. After this, everything will work seamlessly as you can see the execution. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 class BasicInterceptor implements Interceptor { String credentials; BasicInterceptor(String id, String password) { credentials = Credentials.basic(id, password); } @NotNull @Override public Response intercept(@NotNull Chain chain) throws IOException { Request request = chain.request(); Request.Builder builder = request.newBuilder().header("Authorization", credentials); return chain.proceed(builder.build()); } } public class ServiceLocatorProducer implements Producer { private OkHttpClient client = new OkHttpClient.Builder().build(); private LoadingCache> cache; public static final String CACHE_KEY = "service-map"; public static final String KAFKA_TOPIC_KEY = "kafka_topic"; public static final String SERVICE_LOCATOR_BASE_URL = "http://localhost:8000/kafka-service-gw/"; private Properties properties; private KafkaProducer kafkaProducer; private void initCache() throws ExecutionException { cache = CacheBuilder.newBuilder() .maximumSize(10) .expireAfterWrite(5, TimeUnit.SECONDS) .build( new CacheLoader>() { public Map load(String id) throws IOException { final Map svcMap = getServiceConfiguration(); return svcMap; } } ); } private void createProducer(Properties properties) throws ExecutionException { properties.put(BOOTSTRAP_SERVERS_CONFIG, cache.get(CACHE_KEY).get(BOOTSTRAP_SERVERS_CONFIG)); System.out.println(cache.get(CACHE_KEY).get(BOOTSTRAP_SERVERS_CONFIG)); this.properties = properties; kafkaProducer = new KafkaProducer(properties); } ServiceLocatorProducer(Properties properties) throws ExecutionException { initCache(); createProducer(properties); } String getTopic() throws ExecutionException { return cache.get(CACHE_KEY).get(KAFKA_TOPIC_KEY); } public Map getServiceConfiguration() throws IOException { OkHttpClient client = new OkHttpClient.Builder() .callTimeout(5, TimeUnit.MINUTES) .connectTimeout(5, TimeUnit.MINUTES) .addInterceptor(new BasicInterceptor("user1", "password1")) .build(); Map kafkaSvcLocMap = new HashMap<>(); String topic = getTopicConfiguraion(client); kafkaSvcLocMap.put(KAFKA_TOPIC_KEY, topic); String bootstrapServersConfig = getBootstrapServersConfig(client); kafkaSvcLocMap.put(BOOTSTRAP_SERVERS_CONFIG, bootstrapServersConfig); return kafkaSvcLocMap; } @NotNull private String getBootstrapServersConfig(OkHttpClient client) throws IOException { Request request = new Request.Builder() .url(SERVICE_LOCATOR_BASE_URL + "kafka_clusters?domain=example.org") .build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); JsonObject jsonObject = JsonParser.parseString(response.body().string()).getAsJsonObject(); System.out.println("bootstrap:" + jsonObject.get("bootstrap_servers").getAsString()); return jsonObject.get("bootstrap_servers").getAsString(); } @NotNull private String getTopicConfiguraion(OkHttpClient client) throws IOException { Request request = new Request.Builder() .url(SERVICE_LOCATOR_BASE_URL + "channels?channel_name=channel1") .build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); JsonObject jsonObject = JsonParser.parseString(response.body().string()).getAsJsonObject(); System.out.println(jsonObject.get("resolved_value").getAsString()); JsonObject innerObject = JsonParser.parseString(jsonObject.get("resolved_value").getAsString()).getAsJsonObject(); System.out.println(innerObject.get("topic1")); return innerObject.get("topic1").getAsString(); } @Override public Future send(ProducerRecord producerRecord) { return send(producerRecord, null); } @Override public Future send(ProducerRecord producerRecord, Callback callback) { String bootstrapServers = null; String topic = null; try { bootstrapServers = cache.get(CACHE_KEY).get(BOOTSTRAP_SERVERS_CONFIG); topic = cache.get(CACHE_KEY).get(KAFKA_TOPIC_KEY); } catch (ExecutionException e) { throw new RuntimeException(e); } if (this.properties.get(BOOTSTRAP_SERVERS_CONFIG).equals(bootstrapServers) && producerRecord.topic().equals(topic)) { return kafkaProducer.send(producerRecord, callback); } else { System.out.printf( "Need to update bootstrap servers config to %s and the topic config to %s and create a new Producer\n", bootstrapServers, topic); this.close(); properties.put(BOOTSTRAP_SERVERS_CONFIG, bootstrapServers); kafkaProducer = new KafkaProducer(properties); ProducerRecord newRecord = new ProducerRecord<>(topic, producerRecord.key(), producerRecord.value()); return kafkaProducer.send(newRecord, callback); } } Kafka Producer App Typically, the producer application would include all the properties needed to successfully publish records to the Kafka cluster (especially the 2 key things: 1/ Bootstrap servers, 2/ Topic). Like shown below, the ServiceLocatorProducer does the magic to get the right bootstrap servers and topic (instead of the commented out static information). 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 public class App { public static void main(String[] args ) throws Exception, ExecutionException, InterruptedException { Properties config = new Properties(); // Not adding the bootstrap.servers config because it will be retrieved automatically config.put(ACKS_CONFIG, "all"); config.put(KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getCanonicalName()); config.put(VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getCanonicalName()); String [] keys = {"joe", "jill", "justie"}; String [] values = {"crease", "myers", "hill"}; try (final ServiceLocatorProducer producer = new ServiceLocatorProducer<>(config)) { final Random rnd = new Random(); final int numMessages = 10000; for (int i = 0; i < numMessages; i++) { String user = keys[rnd.nextInt(keys.length)]; String item = values[rnd.nextInt(values.length)]; // topic is obtained automatically from the producer and updated if it is different // when we receive the topic from the RecordMetadata received from the send method AtomicReference topic = new AtomicReference<>(producer.getTopic()); producer.send( new ProducerRecord<>(topic.get(), user, item), (event, ex) -> { if (ex != null) ex.printStackTrace(); else { System.out.printf("Produced event to topic %s: key = %-10s value = %s%n", topic, user, item); if (!topic.get().equals(event.topic())) { topic.set(event.topic()); } } }); // Only to demonstrate the change in configurations Thread.sleep(100); } System.out.printf("%s events were produced to topic %s%n", numMessages, producer.getTopic()); } } } Kafka Producer in Action Just showing the excerpts from the full execution here. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 C:\Users\nragh\.jdks\corretto-11.0.22\bin\java.exe "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2023.2.2\lib\idea_rt.jar=55727:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2023.2.2\bin" -Dfile.encoding=UTF-8 -classpath C:\Users\nragh\IdeaProjects\kafka-producer\target\classes;C:\Users\nragh\.m2\repository\org\apache\kafka\kafka-clients\7.0.1-ccs\kafka-clients-7.0.1-ccs.jar;C:\Users\nragh\.m2\repository\com\github\luben\zstd-jni\1.5.0-2\zstd-jni-1.5.0-2.jar;C:\Users\nragh\.m2\repository\org\lz4\lz4-java\1.7.1\lz4-java-1.7.1.jar;C:\Users\nragh\.m2\repository\org\xerial\snappy\snappy-java\1.1.8.1\snappy-java-1.1.8.1.jar;C:\Users\nragh\.m2\repository\org\slf4j\slf4j-api\1.7.30\slf4j-api-1.7.30.jar;C:\Users\nragh\.m2\repository\org\apache\commons\commons-lang3\3.14.0\commons-lang3-3.14.0.jar;C:\Users\nragh\.m2\repository\com\squareup\okhttp3\okhttp\4.12.0\okhttp-4.12.0.jar;C:\Users\nragh\.m2\repository\com\squareup\okio\okio\3.6.0\okio-3.6.0.jar;C:\Users\nragh\.m2\repository\com\squareup\okio\okio-jvm\3.6.0\okio-jvm-3.6.0.jar;C:\Users\nragh\.m2\repository\org\jetbrains\kotlin\kotlin-stdlib-common\1.9.10\kotlin-stdlib-common-1.9.10.jar;C:\Users\nragh\.m2\repository\org\jetbrains\kotlin\kotlin-stdlib-jdk8\1.8.21\kotlin-stdlib-jdk8-1.8.21.jar;C:\Users\nragh\.m2\repository\org\jetbrains\kotlin\kotlin-stdlib\1.8.21\kotlin-stdlib-1.8.21.jar;C:\Users\nragh\.m2\repository\org\jetbrains\annotations\13.0\annotations-13.0.jar;C:\Users\nragh\.m2\repository\org\jetbrains\kotlin\kotlin-stdlib-jdk7\1.8.21\kotlin-stdlib-jdk7-1.8.21.jar;C:\Users\nragh\.m2\repository\com\google\guava\guava\33.2.1-jre\guava-33.2.1-jre.jar;C:\Users\nragh\.m2\repository\com\google\guava\failureaccess\1.0.2\failureaccess-1.0.2.jar;C:\Users\nragh\.m2\repository\com\google\guava\listenablefuture\9999.0-empty-to-avoid-conflict-with-guava\listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar;C:\Users\nragh\.m2\repository\com\google\code\findbugs\jsr305\3.0.2\jsr305-3.0.2.jar;C:\Users\nragh\.m2\repository\org\checkerframework\checker-qual\3.42.0\checker-qual-3.42.0.jar;C:\Users\nragh\.m2\repository\com\google\errorprone\error_prone_annotations\2.26.1\error_prone_annotations-2.26.1.jar;C:\Users\nragh\.m2\repository\com\google\j2objc\j2objc-annotations\3.0.0\j2objc-annotations-3.0.0.jar;C:\Users\nragh\.m2\repository\com\google\code\gson\gson\2.11.0\gson-2.11.0.jar com.platformatory.App {"topic1": "users", "topic2": "users-1"} "users" bootstrap:localhost:9092,localhost:9093,localhost:9094 localhost:9092,localhost:9093,localhost:9094 SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details. Produced event to topic users: key = joe value = myers Produced event to topic users: key = joe value = crease Produced event to topic users: key = justie value = myers Produced event to topic users: key = jill value = hill Produced event to topic users: key = jill value = hill Produced event to topic users: key = joe value = hill Produced event to topic users: key = justie value = hill Produced event to topic users: key = justie value = crease Produced event to topic users: key = joe value = myers ... bootstrap:localhost:9092,localhost:9093 Need to update bootstrap servers config to {localhost:9092,localhost:9093} and the topic config to {users-1} and create a new Producer Produced event to topic users-1: key = joe value = crease Produced event to topic users-1: key = justie value = crease Produced event to topic users-1: key = joe value = myers Produced event to topic users-1: key = justie value = crease Produced event to topic users-1: key = justie value = myers Produced event to topic users-1: key = jill value = hill Produced event to topic users-1: key = justie value = hill Produced event to topic users-1: key = joe value = hill Produced event to topic users-1: key = jill value = myers Produced event to topic users-1: key = justie value = hill Produced event to topic users-1: key = jill value = hill Produced event to topic users-1: key = joe value = hill ... Kafka Consumer Just like the facade created by the Kafka Producer, we do the same here called the ServiceLocatorConsumer, which routes all the calls to the internal Kafka Consumer object. Also, just like the ServiceLocatorProducer, it calls the Catalog Service and obtains the same 2 key properties needed to consume data. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 class BasicInterceptor implements Interceptor { String credentials; BasicInterceptor(String id, String password) { credentials = Credentials.basic(id, password); } @NotNull @Override public Response intercept(@NotNull Chain chain) throws IOException { Request request = chain.request(); Request.Builder builder = request.newBuilder().header("Authorization", credentials); return chain.proceed(builder.build()); } } public class ServiceLocatorConsumer implements Consumer { private OkHttpClient client; private LoadingCache> cache; public static final String CACHE_KEY = "service-map"; public static final String KAFKA_TOPIC_KEY = "kafka_topic"; public static final String SERVICE_LOCATOR_BASE_URL = "http://localhost:8000/kafka-service-gw/"; private Properties properties; private KafkaConsumer kafkaConsumer; public ServiceLocatorConsumer(Map configs) { kafkaConsumer = new KafkaConsumer<>(configs); } private void initCache() throws ExecutionException { cache = CacheBuilder.newBuilder() .maximumSize(100) .expireAfterWrite(5, TimeUnit.SECONDS) .build( new CacheLoader>() { public Map load(String id) throws IOException { final Map svcMap = getServiceConfiguration(); return svcMap; } } ); } private void createConsumer(Properties properties) throws ExecutionException { properties.put(BOOTSTRAP_SERVERS_CONFIG, cache.get(CACHE_KEY).get(BOOTSTRAP_SERVERS_CONFIG)); System.out.println(cache.get(CACHE_KEY).get(BOOTSTRAP_SERVERS_CONFIG)); this.properties = properties; kafkaConsumer = new KafkaConsumer<>(properties); } public ServiceLocatorConsumer(Properties properties) throws ExecutionException { client = new OkHttpClient.Builder().build(); initCache(); createConsumer(properties); } public Map getServiceConfiguration() throws IOException { OkHttpClient client = new OkHttpClient.Builder() .callTimeout(5, TimeUnit.MINUTES) .connectTimeout(5, TimeUnit.MINUTES) .addInterceptor(new BasicInterceptor("user1", "password1")) .build(); Map kafkaSvcLocMap = new HashMap<>(); String topic = getTopicConfiguraion(client); kafkaSvcLocMap.put(KAFKA_TOPIC_KEY, topic); String bootstrapServersConfig = getBootstrapServersConfig(client); kafkaSvcLocMap.put(BOOTSTRAP_SERVERS_CONFIG, bootstrapServersConfig); return kafkaSvcLocMap; } @NotNull private String getBootstrapServersConfig(OkHttpClient client) throws IOException { Request request = new Request.Builder() .url(SERVICE_LOCATOR_BASE_URL + "kafka_clusters?domain=example.org") .build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); JsonObject jsonObject = JsonParser.parseString(response.body().string()).getAsJsonObject(); System.out.println("bootstrap:" + jsonObject.get("bootstrap_servers").getAsString()); return jsonObject.get("bootstrap_servers").getAsString(); } @NotNull private String getTopicConfiguraion(OkHttpClient client) throws IOException { Request request = new Request.Builder() .url(SERVICE_LOCATOR_BASE_URL + "channels?channel_name=channel1") .build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); JsonObject jsonObject = JsonParser.parseString(response.body().string()).getAsJsonObject(); System.out.println(jsonObject.get("resolved_value").getAsString()); JsonObject innerObject = JsonParser.parseString(jsonObject.get("resolved_value").getAsString()).getAsJsonObject(); System.out.println(innerObject.get("topic1")); return innerObject.get("topic1").getAsString(); } @Override public ConsumerRecords poll(long l) { return kafkaConsumer.poll(l); } @Override public ConsumerRecords poll(Duration duration) { String bootstrapServers = null; String topic = null; try { bootstrapServers = cache.get(CACHE_KEY).get(BOOTSTRAP_SERVERS_CONFIG); topic = cache.get(CACHE_KEY).get(KAFKA_TOPIC_KEY); } catch (ExecutionException e) { throw new RuntimeException(e); } if (!this.properties.get(BOOTSTRAP_SERVERS_CONFIG).equals(bootstrapServers) || !this.listTopics().containsKey(topic)) { System.out.printf( "Need to update bootstrap servers config to %s from %s and create a new Consumer\n", bootstrapServers, properties.get(BOOTSTRAP_SERVERS_CONFIG)); properties.put(BOOTSTRAP_SERVERS_CONFIG, bootstrapServers); this.unsubscribe(); this.close(); kafkaConsumer = new KafkaConsumer<>(properties); kafkaConsumer.subscribe(Arrays.asList(topic)); } return kafkaConsumer.poll(duration); } Kafka Consumer App Just like the Kafka Producer App, the Consumer App instantiates the ServiceLocatorConsumer and seamlessly starts consuming from the obtained topic. You can see how the commented out code for the bootstrap servers and the topic show the dynamic nature of the whole system. Also notice that if a configuration change happens during the poll, we automatically refresh the bootstrap servers or the topic configuration and take care of: 1/ updating the bootstrap servers, 2/ on a topic change, we unsubscribe to the previous topics, close the consumer, create a new consumer and subscribe to the new topic(s). Post this, everything gets back to normal. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 public class App { public static void main( String[] args ) throws ExecutionException, InterruptedException { Properties config = new Properties(); try { config.put("client.id", InetAddress.getLocalHost().getHostName()); } catch (UnknownHostException e) { throw new RuntimeException(e); } // Not adding the bootstrap.servers config because it will be retrieved automatically config.put(AUTO_OFFSET_RESET_CONFIG, "earliest"); config.put(GROUP_ID_CONFIG, "kafka-java-consumer"); config.put(KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getCanonicalName()); config.put(VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getCanonicalName()); // topic is obtained automatically from the producer and updated if it is different // when we receive the topic from the ConsumerRecord received from the poll method try (final ServiceLocatorConsumer consumer = new ServiceLocatorConsumer<>(config)) { consumer.subscribe(Arrays.asList(consumer.getTopic())); while (true) { ConsumerRecords records = consumer.poll(Duration.ofMillis(100)); for (ConsumerRecord record : records) { String key = record.key(); String value = record.value(); String topic = record.topic(); System.out.println( String.format("Consumed event from topic %s: key = %-10s value = %s", topic, key, value)); } } } } } Kafka Consumer in Action 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 C:\Users\nragh\.jdks\corretto-11.0.22\bin\java.exe "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2023.2.2\lib\idea_rt.jar=55738:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2023.2.2\bin" -Dfile.encoding=UTF-8 -classpath C:\Users\nragh\IdeaProjects\kakfa-consumer\target\classes;C:\Users\nragh\.m2\repository\org\apache\kafka\kafka-clients\7.6.1-ce\kafka-clients-7.6.1-ce.jar;C:\Users\nragh\.m2\repository\io\confluent\telemetry-events-api\7.6.1-ce\telemetry-events-api-7.6.1-ce.jar;C:\Users\nragh\.m2\repository\com\github\luben\zstd-jni\1.5.5-1\zstd-jni-1.5.5-1.jar;C:\Users\nragh\.m2\repository\org\lz4\lz4-java\1.8.0\lz4-java-1.8.0.jar;C:\Users\nragh\.m2\repository\org\xerial\snappy\snappy-java\1.1.10.5\snappy-java-1.1.10.5.jar;C:\Users\nragh\.m2\repository\org\slf4j\slf4j-api\1.7.36\slf4j-api-1.7.36.jar;C:\Users\nragh\.m2\repository\com\fasterxml\jackson\core\jackson-databind\2.11.0\jackson-databind-2.11.0.jar;C:\Users\nragh\.m2\repository\com\fasterxml\jackson\core\jackson-annotations\2.11.0\jackson-annotations-2.11.0.jar;C:\Users\nragh\.m2\repository\com\fasterxml\jackson\core\jackson-core\2.11.0\jackson-core-2.11.0.jar;C:\Users\nragh\.m2\repository\org\apache\commons\commons-lang3\3.14.0\commons-lang3-3.14.0.jar;C:\Users\nragh\.m2\repository\com\squareup\okhttp3\okhttp\4.12.0\okhttp-4.12.0.jar;C:\Users\nragh\.m2\repository\com\squareup\okio\okio\3.6.0\okio-3.6.0.jar;C:\Users\nragh\.m2\repository\com\squareup\okio\okio-jvm\3.6.0\okio-jvm-3.6.0.jar;C:\Users\nragh\.m2\repository\org\jetbrains\kotlin\kotlin-stdlib-common\1.9.10\kotlin-stdlib-common-1.9.10.jar;C:\Users\nragh\.m2\repository\org\jetbrains\kotlin\kotlin-stdlib-jdk8\1.8.21\kotlin-stdlib-jdk8-1.8.21.jar;C:\Users\nragh\.m2\repository\org\jetbrains\kotlin\kotlin-stdlib\1.8.21\kotlin-stdlib-1.8.21.jar;C:\Users\nragh\.m2\repository\org\jetbrains\annotations\13.0\annotations-13.0.jar;C:\Users\nragh\.m2\repository\org\jetbrains\kotlin\kotlin-stdlib-jdk7\1.8.21\kotlin-stdlib-jdk7-1.8.21.jar;C:\Users\nragh\.m2\repository\com\google\guava\guava\33.2.1-jre\guava-33.2.1-jre.jar;C:\Users\nragh\.m2\repository\com\google\guava\failureaccess\1.0.2\failureaccess-1.0.2.jar;C:\Users\nragh\.m2\repository\com\google\guava\listenablefuture\9999.0-empty-to-avoid-conflict-with-guava\listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar;C:\Users\nragh\.m2\repository\com\google\code\findbugs\jsr305\3.0.2\jsr305-3.0.2.jar;C:\Users\nragh\.m2\repository\org\checkerframework\checker-qual\3.42.0\checker-qual-3.42.0.jar;C:\Users\nragh\.m2\repository\com\google\errorprone\error_prone_annotations\2.26.1\error_prone_annotations-2.26.1.jar;C:\Users\nragh\.m2\repository\com\google\j2objc\j2objc-annotations\3.0.0\j2objc-annotations-3.0.0.jar;C:\Users\nragh\.m2\repository\com\google\code\gson\gson\2.11.0\gson-2.11.0.jar com.platformatory.App {"topic1": "users", "topic2": "users-1"} "users" bootstrap:localhost:9092,localhost:9093,localhost:9094 localhost:9092,localhost:9093,localhost:9094 SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details. Consumed event from topic users: key = justie value = myers Consumed event from topic users: key = justie value = crease Consumed event from topic users: key = justie value = crease Consumed event from topic users: key = justie value = crease Consumed event from topic users: key = justie value = crease Consumed event from topic users: key = justie value = hill Consumed event from topic users: key = justie value = myers Consumed event from topic users: key = justie value = myers ... bootstrap:localhost:9092,localhost:9093 Need to update bootstrap servers config to {localhost:9092,localhost:9093} from {localhost:9092,localhost:9093,localhost:9094} and create a new Consumer Consumed event from topic users-1: key = joe value = crease Consumed event from topic users-1: key = joe value = myers Consumed event from topic users-1: key = joe value = hill Consumed event from topic users-1: key = joe value = hill Consumed event from topic users-1: key = joe value = hill Consumed event from topic users-1: key = joe value = myers Consumed event from topic users-1: key = justie value = crease Consumed event from topic users-1: key = justie value = crease Consumed event from topic users-1: key = justie value = myers Consumed event from topic users-1: key = justie value = hill Consumed event from topic users-1: key = justie value = hill ... Python Implementation Coming soon… Conclusion Creating a system that helps a centralized Kafka infrastructure team to easily create, label and vend information reduces common problems and dependencies. Same benefits are passed on to the producers and consumers thus creating a scalable system/organization. --- # A Primer on Streaming Databases URL: https://platformatory.io/blog/primer-on-streaming-databases/ Published: 2024-07-11 Authors: Avinash Upadhyaya Categories: Streaming Databases, Stream Processing, Kafka, ksqlDB Stream Processing In the modern era of digitalization, data needs to be made available for making important business decisions and insights in “real-time”. The definition of “real-time” varies with use-cases and is measured by the latency from the source to the destination. For example, use-cases such as High Frequency Trading (HFT) require sub microsecond latency and are not attainable through any software-based stream processing system but through FPGAs. Further down the spectrum, we have another hard real-time use case of self-driving cars and industrial automation, which can tolerate a few milliseconds of latency. On the other end, we have the traditional batch processing, which can vary from minutes to hours to even days. Challenges with Stream Processing For the rest of the use cases, we can rely on a stream processing system that processes data in “real-time”. For such real-time processing systems, there are constraints within the system, such as constraints on how quickly the data can be made available for processing from various other systems. It is usually the weakest link in the chain that contributes to the constraints. This makes stream processing in “real-time” a hard problem to solve. The challenge with stream processing is that stream processing operations are actually defined on the future state of data, i.e., the system needs to be aware of how to process data that arrives in the future. This is different from conventional databases, even data warehouses, or the general landscape of OLAP systems, where the computation is done on data that already exists. Another major challenge with stream processing is that the data is unbounded and unpredictable. As with any distributed system, nothing is trustworthy, especially the network. Therefore, unbounded data also means that the data can arrive late or not in order. The stream processing system should be able to handle these challenges and process data while providing a correctness and consistency guarantee. Stream Processing Frameworks There are many systems built to solve the challenges of stream processing in “real-time”. A stream processing engine is capable of processing data as it arrives and handling data that arrives in the future. The processing typically involves filtering, transforming, joining, and aggregating one or more streams of data. Some of the popular frameworks for stream processing are Apache Storm, Apache Samza, Apache Ignite, Apache Flink, Kafka Streams, and Apache Spark Streaming. Each of these frameworks or engines provides unique ways of processing data, with various pros and cons. Among these, Apache Flink is a popular project that can handle both streaming and batch processing. Such stream processing engines provide an interface in a programming language such as Java or Python and typically allow performing low-level computations on streaming data. SQL: Universal language for data Stream processing engines that provide low-level APIs are great for use cases that require either direct access to the state store or processing data at a granular level. However, a lot of use cases can be implemented without writing a lot of boilerplate code and building bloated code bases. SQL has emerged as a solution to this problem, with some of the stream processing engines, such as Apache Flink and Apache Spark Streaming, supporting it. SQL has stood the test of time and is a query language familiar to most data engineers. It solves the developer experience problem for stream processing and allows expressing the computation to be performed in a simple DSL that is understood not just by data engineers but also by data scientists or statisticians. This allows expressing the processing operations as SQL like statements instead of functional code. Streaming Databases The use of SQL for stream processing led to the emergence of a new category of stream processing engines called streaming databases. Streaming databases provide an interface for stream processing while abstracting some of the complexities involved in running a distributed system for stream processing. KsqlDB was one of the earliest projects in the space and provided an SQL interface on top of Kafka and Kafka Streams. RisingWave, Materialize, and DeltaStream are some of the leading and emerging projects. Streaming Databases vs Stream Processing vs Real Time OLAP Although both a stream processing engine and a streaming database serve the same purpose, they are different by definition. A stream processing engine uses a local state, which is distributed across all workers that the framework uses. These state stores might be queryable as well. Whereas a streaming database has storage as a first class concern and decouples the storage and compute. In the case of a stream processing framework, the data flow is in the control of the person writing the job. Streaming databases hide the stream processing from the user and have query planners, optimizers that do the heavy lifting for the data flow. Streaming databases are more declarative, while stream processing frameworks are typically imperative. Real time analytical databases such as Apache Druid, Apache Pinot, or Clickhouse, on the other hand, are meant for querying data in real-time post ingestion. These databases handle ad-hoc and user facing analytics. Whereas a streaming database is meant to work on data before it is ingested into a RTOLAP database for querying. Comparing Streaming Databases While evaluating a streaming database, asking a few questions about the features, design, and capabilities can help. Sources and Sinks One of the major considerations is regarding the supported sources and sinks of data. Does it have direct support for Postgres, Oracle CDC, or Change Data Capture from various other platforms out of the box? This allows saving hope and maintaining an additional component, such as Debezium, for the CDC. Another important source/sink is Kafka. Since Kafka has emerged as the de-facto protocol for streaming, it is important that the streaming database support the Kafka protocol for source and sink. SQL One of the primary reasons to adopt a streaming database is the developer experience and the abstraction that it provides over a stream processing framework. A key aspect is the dialect of SQL that is supported. For example, many streaming databases are Postgres wire protocol compliant, which helps developers familiar with Postgres adopt it with ease. Typical use-cases in stream processing involve enriching data; hence, it is important to look at the JOINs supported. Finally, the streaming database should have support for various schema formats, such as Avro, JSON, Protobuf, etc. Consistency Model A key concern with stream processing is the correctness of the data, which implies the streaming database should support transactions or atleast atomicity of the data. In any distributed system, data might arrive later than intended, and the system should be capable of handling such late-arriving data. An important consideration is the types of windows supported for joins and aggregations. Watermarking has traditionally been a concept in the realm of stream processing frameworks, but there have been recent improvements that bring concepts like watermarking into the world of streaming databases. Support for watermarking is another consideration for evaluation. Extensibility Even if the streaming database does not support all transformations or operations desired, it should allow the user to extend the capabilities of the system using a User Defined Function (UDF). For UDFs, the languages supported and the level of extensibility are key factors for evaluation. Fault Tolerance An important aspect of any distributed system dealing with mission critical data is the ability to recover from failure without losing data. One should understand the state management and the Recovery Point Objective (RPO) / Recovery Time Objective (RTO) that the streaming database supports. Maturity When evaluating any software, the maturity and age of the software is a basic criteria for evaluation. Another relevant criteria is the adoption of the streaming database. If the streaming database is adopted by companies that are running it at scale with a proven record, it adds to the credibility of the database. Real benchmarks from customers help understand the performance of the system better. Architecture Finally, understanding the implementation details helps in designing and troubleshooting the stream processing better. An aspect of evaluation is understanding the data flow model, the key primitives, and user facing APIs / constructs. Comparison of 3 OSS streaming databases For this blog post, we will be providing a comparison between three open source databases - KsqlDB, RisingWave, and Materialize. We will briefly compare them across the previously mentioned factors and provide a reference for evaluation. KsqlDB KsqlDB provides an SQL DSL on top of Kafka Streams, and therefore it inherits both the advantages and disadvantages of Kafka Streams. KsqlDB translates the SQL query and plans the processor topology before executing a Kafka Streams application behind the scenes. KSQL has two processing primitives - Streams and Tables. Tables are essentially a compacted stream. KSQL is not ANSI SQL complaint, hence, the syntax is custom. KsqlDB does not support transactions. KsqlDB integrates out-of-the-box with Confluent Schema Registry, supporting JSON, Avro, JSON Schema, and Protobuf formats. KSQL supports Stream-Stream, Stream-Table joins, and in-general, n-way joins. However, there are certain limitations to how joins can be done. In terms of windows, KSQL supports Tumbling, Hopping, and Session windows. There is no concept of watermarking in ksqlDB, however, there is a concept of grace periods. If the late arriving data does not arrive within a specific upper bound, then the window is closed. For the state store, ksqlDB uses RocksDB, and the state store is backed up through a changelog topic. There is no snapshotting or checkpointing of data. In the event of a disaster, ksqlDB can replay the changelog topic and reconstruct the state. This is a time consuming process, and hence the RTO is always > 0. KsqlDB supports Kafka for source and sink. However, it also allows configuring Kafka connectors using SQL, which implies that all the Kafka connectors can be considered a source and sink for ksqlDB. KsqlDB allows writing custom processing logic using Java-based UDFs. KsqlDB is backed by Confluent and is open source with a Confluent Community License. Materialize Materialize is based on the TimelyFlow data model and written in Rust. The processing is based on Materialized Views, which are like an aggregation of streams. Materialize also has indexes, which are like tables used for enrichment. The SQL used in Materialize is fully wire compatible with Postgres. Materialize supports transactions as well. Materialize supports JSON, Avro, and Protobuf formats but does not support JSON Schema yet. Materialize supports all forms of joins, including varieties such as lateral joins or cartesian cross joins. For windowing, sliding and TTL windows are supported. Materialize is based on the timely differential data flow model, which uses the concept of arrangements to store the state. However, these are stored in memory, and the fault tolerance for these is unclear. Materialize ensures consistency using a concept called virtual timestamps and provides consistency guarantees for input, internal, and output. Materialize supports Kafka, Postgres, MySQL, and webhooks for sources and Kafka for sinking. There is no support for UDFs, however, there is extensive support for SQL functions. Materialize is maintained by a company with the same name and is under a Business Source License (BSL). RisingWave RisingWave is also written in Rust and has Materialized Views and Indexes as the primary processing primitives. RisingWave is fully wire compatible with Postgres and supports transactions. RisingWave supports transactions as well. RisingWave supports Avro, JSON, and Protobuf, along with a few dialects of JSON such as Canal JSON and Maxwell JSON. In terms of joins, RisingWave supports inner and outer joins, with Tumbling and Hopping windows supported. The state store in RisingWave is a custom state store, which is not quite RocksDB and is called Hammock. Hammock uses S3 for storage and supports checkpointing for fault tolerance. RisingWave adopts the Chandy–Lamport algorithm to create checkpoints. RisingWave supports watermarking, similar to Apache Flink. RisingWave supports Kafka, Pulsar, S3, Kinesis, Google Pub Sub, and Postgres/MySQL CDC for sources and Kafka, MySQL, Postgres, Kinesis, Iceberg, and Delta Lake for sinking. UDFs can be written in Python for extensibility. RisingWave is maintained by a company with the same name and is open source under an Apache 2.0 license. --- # A Leaderless Future for Kafka: Why Object Storage Is Going Mainstream URL: https://platformatory.io/blog/a-leaderless-future-kafka-streaming/ Published: 2024-07-10 Authors: Pavan Keshavamurthy Categories: Kafka, Distributed Systems, Real-time, Platform Engineering As of 2024, Apache Kafka is almost a teenager. A project & community that has been nothing short of pivotal and truly deserving of the category creator hall of fame. However, the teenage years are a little crazy. The fundamentals are still strong, but Apache Kafka is almost legacy is a little behind But let’s state it right at the onset: Building still in the (mostly) on-premise era, The founders of Kafka were true visionaries who got a lot right, straight from the onset. Building on JVM (memory safety, GC, for better or worse), persistence as a first class concern , a design focused on commodity HDDs (optimized for sequential I/O), zero copy optimizations, all on top of a relatively minimalistic API surface, and tons of bolt-ons organically evolved over the years. Till date, every KIP still conforms to a spirit of performance focus, a design ethos that is beyond question. Justifiably, Kafka has emerged as the de-facto mechanism for data exchange. The Kafka API has also become a gold standard beyond its own, self-branded implementation. It is now supported by an increasing mushroom cloud of technologies, both OSS and commercial, tackling the same class of problems Kafka originally set out to. Although for the most part, the USP is about gaining an “install base” audience, touting “compatibility and drop-in replacement” – a classic market focused adoption play, but at any rate, standardizing on someone else’s API is still the deepest form of flattery you can get in tech. As of 2024, every hyperscaler provides a Kafka (or compatible) managed service and there are now, prospectively best in breed Kafka-esque platforms emerging beyond the Apache Fn project Everything is a product of its times and Kafka is no different. While the community still keeps up (which we shall discuss later on), it only does so with much baggage and design constraints that it was born with, some of which are just structural in nature. Some things are still less right and more wrong Over the years, there has been a greater convergence of what were kafka’s deficits, but it also falls into the zone (in 20:20 hindsight) of trends that green-field, cloud native b(l)oomer projects have been beneficiaries of. Let’s look at a few dimensions of differentiation: A simple(r) distribution: aka, a single binary. No Zookeeper (or a better Zookeeper) Squeezing the last drop of performance: aka, getting rid of the JVM (and it’s concurrency model) A modern approach to storage: aka separating storage from compute (and more loosely, tiered storage) but also SSDs. And the radical new idea of completely doing away with disks. Operator Experience: aka, something better than the clunky kafka run class tools A longer exhaustive list: Multi-tenancy, 2PC, Adaptive Partitioning, Proxies (and more) For example, Pulsar was the first to objectively address (1) and parts of (5). But it did introduce additional complexity with Apache Bookkeeper. JVM has been a perennial bottleneck and therefore a C++ based rewrite like Redpanda, armed with a Seastar core and a storage layer for modern SSDs, beats Kafka benchmarks on all of throughput, latency and node count relatively easily in most scenarios. WarpStream and AutoMQ take the storage debate to the holy grail of cloud native architectures - ie, to S3. Confluent on its own part has built several enterprise features, including tiered storage, but also what is probably the most robust DevX and OperatorX around Kafka. Obviously these are available in self hosted and BYOC variations. Not to speak of the cloud-first offerings, such as Confluent Cloud itself, but also the comparable (atleast Kafka for kafka terms) AWS MSK serverless, Azure Event Hubs and most recently, Google entering the Kafka market with Apache Kafka for BigQuery. Infact, the distinction is so stark that the marketing pitch from nearly everyone involves some flavor of 10X differentiation from self-hosted Apache Kafka, including Confluent, Apache Kafka’s corporate steward. The truth is that the Apache Fn project (and together with Confluent which employes a number of committers) has addressed most of these challenges highlighted above as differentiation, but it has largely been as a follower. The basic fact is that open source now lags behind. Streaming is still a low latency niche Streaming systems are fundamentally designed to optimize for incremental processing and lower latency. While there’s no doubt about the value of real-time data, acting upon data in motion requires a much more comprehensive focus, on a still volatile and maturing stack and many inherent complexities (such as time domain, stateful processing, consistency) which most stakeholders used to batch processing simply don’t fully grok. When asked to tradeoff latency against the costs and complexity of achieving it, we have seen that most businesses tend to make it an easy decision. They can live with a few more seconds (sometimes hours) of latency. TCO is shaping the future of Kafka We talked previously about the mushrooming of the de-novo Kafkaesque. While you would expect this market to be all about the hype of real-time and the art of the possible, ground reality is that sales and adoption conversations are largely led by TCO. TCO is a very subjective and opaque metric that needs quantification of the customer’s operating capability, personnel costs and most importantly tangible opportunity cost. In most cases, this is not an honest conversation between sellers and enterprise buyers. This leads to very contrived forms of differentiation and commercial discounting from vendors of a “must win” nature, relationship plays, package deals, FUD about competition, and often, plain nonsense. At the end of the day, it is pretty simple. In private cloud, on-premise and BYOC environments it reduces to these factors: number of node or core licenses required to guarentee a certain (peak) throughput (lower is better, relative to present state, realistic projections and head-room for growth) Cross-zone / cross-region networking models (and therefore ingress/egress charges) With cloud (and specifically serverless), it boils down to: throughputs (in other words ingress/egress) concurrency, partition counts storage In a world where everyone prefers serverless options on the cloud and a desire to pushdown durability to the vendor, while avoiding cross-AZ surprise billing (down to the cloud provider), the race to the bottom for data infra at the lowest cost will always be won by the holy grail of all data foundations, which is, (drumroll) AWS S3. Or more generally, cloud object storage. But we emphasize S3 because AWS is a first mover for all sorts of things on the cloud and S3 Express 1Z is defining a new frontier by providing consistently sub-10ms latencies directly at the bedrock of durable storage. This would have sounded provocative many years ago, but in 2023-24, in very much the footsteps of every other , a Kafka API on top of S3 directly was just something waiting to be built. This is exactly what WarpStream is doing and although there will be fast followers (sometimes pioneers who grudgingly claim independent discovery of the idea). First movement and execution matters. Acknowledging good competition is good. The writing on the wall is pretty clear. Kafka on the cloud is way more expensive than it needs to be. A Kafka protocol on top of object storage will satisfy the pareto principle for most workloads in a TCO defense. Latency will only get better in times to come. Soon enough, such clusters will be a commodity. Curiously, in this implementation, there are no leaders, replicas or ISR. It definitely foreshadows what the Kafka platform landscape is headed to: a leaderless future. Dumb pipes are a commodity. The value is up the chain So far we have spoken about competitive dynamics. But the surface area of Kafka is actually pretty minimalistic. It mostly provides pub-sub plumbing for a distributed world. Shock absorbers between systems. Big buffers and flood controls. Fire Hoses. Fundamentally pipes though. Dumb pipes at that. However, with good dumb pipes, you can still build a whole ecosystem of tooling. And that’s really where the value lies. Connectors, Stream processing, streaming databases, real-time features, real-time databases, event-driven architecture, ML/AI even. The sum total of all these components and coverage of various cross cutting concerns forms the streaming platform. A platform which you can build multi modal data products on. Instant Data Lakehouse. Far from there One of the architectural advantages of streams as a foundational data primitive, combined with the trends we have discussed, of tiered storage and no disks (object storage) is an interesting innovation in fully embracing Kappa architecture. Continuous streams that hydrate lakes, warehouses and everything in between, but without the need of additional plumbing. The side effects of offloading storage in full part to S3 is that your Kafka log segments can be magically turned into open tables which query engines, warehouses and lakehouses can directly talk to. Or perhaps even more appealing are the likes of DuckDB and a whole ecosystem of an up & coming, headless, composable data stack that layers on top of it. This has profound implications on the cost and economics of data architectures. However, be cautioned: It is still early days and this is largely architecture astronomy with many feature gaps. Batch and streaming do have pretty stark context boundaries and limited shared vocabulary or even good tooling. Even Flink is certainly not there yet. Spark and Spark streaming is fundamentally still a microbatch primitive under the hood. Projects like Beam have a vision but are fundamentally limited by runners they integrate with. Over the course of time, one would expect some truly unified experience and consistent APIs. Perhaps with the advent of Arrow, Ibis Data and the like. Convergence and Divergence Protocols and APIs always outlive platforms. Kakfa certainly enjoys the protocol privilege as it stands. However, in any market that leads to a commodity, it is exceedingly difficult for vendors to keep baselining themselves against an API of another project they don’t control. While open standards such as AsyncAPI and CloudEvents are extant, their vision is pretty narrow and purpose specific to interoperability, rather than as a foundation to streaming. The natural consequence is that while everything in the short term is still converging to Kafka, it is likely that in the long term, market forces will propel vendors to differentiate. For the curious and nerdy, we will have a series to publish about the internals of NATS and Kinesis to begin with. If you are a Kafka user and interested in our technical whitepaper about the Kafka landscape, register your interest here and we will share a copy. It also contains a holistic analysis of the real-time data stack and SWOT plots for Confluent, Redpanda, WarpStreamMSK, Azure Event Hubs and GCP Kafka for BigQuery --- # Unified Access Layer for Kafka Resources: Part 1 URL: https://platformatory.io/blog/unified-access-layer-kafka-resources-part-1/ Published: 2024-07-09 Authors: Pavan Keshavamurthy, Raghavendran Nehru Categories: Kafka, Unified Access Layer, Platform Engineering, Infrastructure Introduction Managing Kafka clusters is all good as a platform team until you have a handful of teams and a handful of clusters. Let’s visit some common scenarios where every platform team has ended up with a mish-mash of ungoverned clusters or topics that eventually needs some garden cleaning (for good reason). You need to move or migrate topics in the same cluster (surprise, Kafka can’t shrink partitions so you will have to create a new topic and replicate to mirror the old). You may need to move or migrate a topic (let’s say with hot, noisy neighbor partitions) to a different cluster altogether You may want to move a whole cluster to better infrastructure (or more commonly because you have a disaster!). You need to change the authentication mechanism and (re)distribute credentials. Your devs are complaining and need help optimizing their configurations (and they have no clue what they’re doing). If you’ve been there, done that and burnt your hands, you’re not alone. The part that makes this all pretty hard in the Kafka world is the nature of Kafka’s API, where clients do much of the song and dance. We have a proposal for a future proofing for all these concerns that includes: The ability to route a client to a specific cluster (bootstrap.servers) dynamically, without having these hardcoded in the client ProTip: Very useful for entire cluster migrations The ability to route a client to a specific topic, based on a higher order messaging or routing primitive, without being joined in the hip with a set of topics ProTip: Very useful for topic migrations, but also routing multiple types of messages to the same topic Credential Mediation Giving clients their auth instruments, dynamically. Potentially references to secret stores or serving the credentials straight up (but ability to rotate on the server-side as well as revoking them on-demand) Configuration profile Ability to provide some of your well optimized for latency, throughput, durability, availability or otherwise just your distillation of best practices for producer, consumer, admin client configurations. Having some abstractions to achieve these cross cutting concerns is a good measure and will yield sanity to platform operators who may need to defer great control to themselves. In general, for large scale use-cases, it is always good to have some insulation and indirection in between kafka clients and the server, ala proxy patterns very popular in the HTTP/REST world. This post intends to propose common solutions (as a series) that would help overcome these problems and in the true spirit of a platform, provide an effective amount of self service. Approach 1: Discover topics through Language specific SDKs and a rule-based routing layer This is a pattern where a language specific SDK handles the following concern, by talking to a metadata or a catalog service. Typically, the client here would, before instantiating a kafka client, locate the target kafka service using A HTTP/REST call to the catalog service (using some form of security: Such as basic auth or OAuth) Express an intent (such as to produce or consume) on a certain topic or domain of topics (such as prefix pattern) OR by the virtue of it’s client ID, be routed to the appropriate cluster Receive the kafka bootstrap location Optionally, mediated credentials for both kafka and typically, schema registry The above, being cached with a TTL Return a Kafka client instance This approach has a wider-domain of applicability, beyond containerized environments, but it does require A secured, metadata or catalog service (run by you) Which ideally has automation for inventory discovery across multiple clusters Combined with routing rules Language specific, idiomatic service locator implementation (“SDK”) And therefore code changes to existing applications including exception handling flowchart LR subgraph PRODUCERS["Producers"] P1("Producer 1") P2("Producer 2") P3("Producer 3") end subgraph CG1["Consumer Group 1"] C1("Consumer 1") end subgraph CG2["Consumer Group 2"] C2("Consumer 1") C3("Consumer 2") end subgraph CG3["Consumer Group 3"] C4("Consumer 1") C5("Consumer 2") end subgraph GW["Rule Based Routing Layer"] direction LR API["APIs (Kong)"] US["Upstream (Catalog Service)"] end subgraph K1["Kafka Cluster 1"] B1["Broker 1"] B2["Broker 2"] B3["Broker 3"] end subgraph K2["Kafka Cluster 2"] B4["Broker 1"] B5["Broker 2"] B6["Broker 3"] end P1 & P2 & P3 -- 1.GetInfo --> GW -- 2.Response --> P1 & P2 & P3 CG1 & CG2 & CG3 -- 1.GetInfo --> GW -- 2.Response --> CG1 & CG2 & CG3 P1 -- 3.Produces --> K1 P2 -- 3.Produces --> K2 P3 -- 3.Produces --> CC API --> US K1 -- 4.Consumes --> CG1 K2 -- 4.Consumes --> CG2 CC -- 4.Consumes --> CG3 %% Styling classDef kafkaStyle fill:#e0f7e9,stroke:#4caf50,stroke-width:2px; class K1,K2 kafkaStyle; We get into the description and implementation details here: Unified Access Layer: Part 2: Rule Based Routing Approach 2: Use a Service Mesh (for Kubernetes Environment) A service mesh (like Istio, Kuma) can be leveraged as a layer to access Kafka resources. It typically includes service discovery mechanisms that allow services to dynamically discover and communicate with each other, and this can be extended to Kafka by enabling services to discover Kafka brokers and other Kafka-related services (like schema registries or Kafka Connect connectors). Understanding Service Mesh and Sidecar Pattern Service Mesh: A service mesh is an infrastructure layer that enables managed, observable, and secure communication between microservices. It typically includes features like traffic management, security, and observability. Sidecar Pattern: In a service mesh, the sidecar pattern involves deploying a helper container (sidecar) alongside each microservice container. This sidecar handles the networking responsibilities such as routing, proxying, and observing traffic. Key Concepts: Local Sidecar Endpoint: Each microservice communicates with its own local sidecar proxy rather than directly with other services or external endpoints. Broker / Mesh Filters: The sidecar uses rules and filters (configured in the service mesh) to manage traffic, including routing requests to the appropriate upstream services. Central idea: You produce to or consume from a local sidecar endpoint (which uses broker / mesh filters to route the request upstream). Let’s dissect this. You produce to or consume from a local sidecar endpoint: Produce: In Kafka terminology, producing refers to sending data (messages) to a Kafka topic. Consume: Consuming refers to retrieving data (messages) from a Kafka topic. Local Sidecar Endpoint: Instead of directly interacting with Kafka brokers, your application sends data to a local sidecar proxy endpoint. This proxy is running in the same pod as your application. Which uses broker / mesh filters: Broker: This typically refers to the Kafka brokers that handle message storage and retrieval. Mesh Filters: These are configurations within the service mesh that dictate how traffic should be managed. Filters can include rules for load balancing, retries, timeouts, security policies, etc. To route the request upstream: Upstream: In networking, upstream refers to the direction towards the service you are communicating with. Here, it means the Kafka brokers. The local sidecar proxy receives the request and, based on the configured filters and routing rules, forwards (or routes) the request to the appropriate Kafka broker. Here’s the overall architecture diagram for this idea. flowchart TD %% Kubernetes environment subgraph K8S ["Kubernetes"] direction TB %% Service Mesh (Istio) subgraph Istio ["Service Mesh (Istio)"] direction TB %% Producer Pods subgraph P1Pod ["Pod: Producer 1"] direction TB P1("Producer 1") P1Envoy["Envoy Proxy (P1)"] Filter1["Mesh Filter (P1)"] P1 -->|Produces To| P1Envoy --> Filter1 end subgraph P2Pod ["Pod: Producer 2"] direction TB P2("Producer 2") P2Envoy["Envoy Proxy (P2)"] Filter2["Mesh Filter (P2)"] P2 -->|Produces To| P2Envoy --> Filter2 end %% Kafka Cluster 1 subgraph K1 ["Kafka Cluster 1"] direction TB subgraph Broker1Pod1 ["Pod: Broker 1"] direction TB Broker1Envoy1["Envoy Proxy (Broker 1)"] Broker1_1("Broker 1") Broker1Envoy1 --> Broker1_1 end subgraph Broker1Pod2 ["Pod: Broker 2"] direction TB Broker1Envoy2["Envoy Proxy (Broker 2)"] Broker1_2("Broker 2") Broker1Envoy2 --> Broker1_2 end subgraph Broker1Pod3 ["Pod: Broker 3"] direction TB Broker1Envoy3["Envoy Proxy (Broker 3)"] Broker1_3("Broker 3") Broker1Envoy3 --> Broker1_3 end Topic1["Topic 1"] Topic2["Topic 2"] end %% Kafka Cluster 2 subgraph K2 ["Kafka Cluster 2"] direction TB subgraph Broker2Pod1 ["Pod: Broker 1"] direction TB Broker2Envoy1["Envoy Proxy (Broker 1)"] Broker2_1("Broker 1") Broker2Envoy1 --> Broker2_1 end subgraph Broker2Pod2 ["Pod: Broker 2"] direction TB Broker2Envoy2["Envoy Proxy (Broker 2)"] Broker2_2("Broker 2") Broker2Envoy2 --> Broker2_2 end subgraph Broker2Pod3 ["Pod: Broker 3"] direction TB Broker2Envoy3["Envoy Proxy (Broker 3)"] Broker2_3("Broker 3") Broker2Envoy3 --> Broker2_3 end Topic3["Topic 3"] Topic4["Topic 4"] end %% Consumer Pods subgraph C1Pod ["Pod: Consumer 1"] direction TB C1("Consumer 1") C1Envoy["Envoy Proxy (C1)"] Filter3["Mesh Filter (C1)"] C1 -->|Consumes From| C1Envoy --> Filter3 end subgraph C2Pod ["Pod: Consumer 2"] direction TB C2("Consumer 2") C2Envoy["Envoy Proxy (C2)"] Filter4["Mesh Filter (C2)"] C2 -->|Consumes From| C2Envoy --> Filter4 end end end %% Connections Filter1 -->|Produces to| Topic1 & Topic2 Filter2 -->|Produces to| Topic3 & Topic4 Topic1 -->|Consumed by| Filter3 Topic3 -->|Consumed by| Filter4 Broker1Envoy1 -->|Manages| Topic1 & Topic2 Broker1Envoy2 -->|Manages| Topic1 & Topic2 Broker1Envoy3 -->|Manages| Topic1 & Topic2 Broker2Envoy1 -->|Manages| Topic3 & Topic4 Broker2Envoy2 -->|Manages| Topic3 & Topic4 Broker2Envoy3 -->|Manages| Topic3 & Topic4 %% Styling classDef kafkaStyle fill:#e0f7e9,stroke:#4caf50,stroke-width:2px; class K1,K2 kafkaStyle; Downsides to using a service mesh: It is another piece of middleware that needs someone familiar with the internals (like Envoy proxy) to be able to operate it. Tenancy: the more tenants, the more valuable it is to operate. Careful planning is needed for policy, automation, tenancy and isolation. Being another piece of the services in the request path requires understanding on configuration, operation and integration within the organization. That with the governance between different teams. Approach 3: Virtualize the Kafka Cluster and Topic (through a Kafka Gateway) In this approach, the gateway (e.g., Conduktor) is a network proxy for Apache Kafka with capabilities that are extensible and customizable through plugins. Here is the architecture diagram to visualize the capabilities. flowchart TD subgraph PRODUCERS["Producers"] P1("Producer 1") P2("Producer 2") end subgraph CG1["Consumer Group 1"] C1("Consumer 1") end subgraph CG2["Consumer Group 2"] C2("Consumer 2") C3("Consumer 3") end subgraph CONSUMERS["Consumers"] CG1 CG2 end subgraph GW["Kafka Gateway"] direction LR AA["Authentication & Authorization"] PL["Plugins"] end subgraph K1["Kafka Cluster"] B1["Broker 1"] B2["Broker 2"] B3["Broker 3"] end subgraph D1["Destinations"] K1 CC["Confluent Cloud"] end subgraph A1["Producers & Consumers"] direction LR PRODUCERS CONSUMERS end P1 & P2 -- Produce --> GW -- Consume --> CG1 & CG2 K1 & CC -- Messages --> GW AA --> PL GW -- Forward ---> K1 & CC classDef kafkaStyle fill:#e0f7e9,stroke:#4caf50,stroke-width:2px; class A1,D1 kafkaStyle; The gateway is deployed between the producers/consumers and the Kafka clusters and because it is Kafka protocol compliant, there are very small changes (like a new bootstrap server) needed for the clients to connect to the gateway. Typically, the gateway provides authentication via the support for security protocols just like the brokers (PLAINTEXT, SSL, SASL SSL, mTLS). The interesting component of the gateway is the Interceptors where we can write the business logic, especially routing the requests which is the central topic here. The gateway can also support processing flow (could be a pipeline of interceptors) where each component of the pipeline can be invoked sequentially during a produce request and the responses from the broker go through the pipeline in the reverse order. Some pros of the approach: being Kafka protocol compliant implies that they can support multiple vendors extensibility of the gateway could bring in operational insights into security, compliance, monitoring and alerting provides centralized management for one team to manage access and configuration Some downsides of the approach: they add latency depending on how they are implemented (Conduktor add latencies in the order of milliseconds) which can increase if encryption is enabled using a custom encryption key. Latency can increase if the processing flow pipeline has a number of plugins. proprietary tools could result in vendor lock-ins initial setup and configration could be complex Approach 4: Discover Topics using a Data Catalog + Self-Service Portal A data catalog allows organizations to managing and discovering data assets (in this case, Kafka clusters/streams, topics, schemas). Depending on the choice of the data catalog, it could support Kafka resource natively or have limited support. Ideally, you would need a data catalog that supports Kafka out-of-the-box. Here are a few options: Apache Atlas: is the only Open Source solution that integrates well with Kafka, provides management and governance of data streams. It helps in Metadata management (tracks lineage and metadata for Kafka topics), Classification (allows classification and tagging of Kafka topics), Search and discovery (easy search and discovery of Kafka streams). Confluent stream catalog: supports Kafka resources (Schemas, Topics, Connectors, Clusters, Environments, Streaming data pipelines, Apache Flink® compute pools) on Confluent Cloud. It offers benefits such as improved metadata management and easier integration with external systems. Other options: GCP supports a catalog for Pub-Sub. AWS Glue Catalog unfortunately has limited support for streams (through the integration with Amazon MSK or Managed Service for Kafka). Azure supports Azure Catalog (similar features like AWS Glue Catalog). Collibra has some limited support for Kafka (apart from Metadata management and governance, it supports data quality checks for streaming data). We can also look at OpenMetadata, Databricks unity catalog and Amundsen among others. For everything else, there’s the Hive metastore. Here’s the architecture diagram for the idea: flowchart TD subgraph PRODUCERS["Producers"] P1("Producer 1") P2("Producer 2") end subgraph CG1["Consumer Group 1"] C1("Consumer 1") end subgraph CG2["Consumer Group 2"] C2("Consumer 2") C3("Consumer 3") end subgraph CONSUMERS["Consumers"] CG1 CG2 end subgraph SSP["Self-Service Portal"] PO1["Portal"] end subgraph DC["Data Catalog for Kafka"] direction LR API["APIs"] MM["Metadata Management & Lineage"] TL["Classification & Tagging"] DG["Data Governance"] DQ["Data Quality"] end subgraph SSPDC["Self-Service Portal & Data Catalog"] direction TB SSP DC end subgraph KC["Kafka Cluster"] B1["Broker 1"] B2["Broker 2"] B3["Broker 3"] end subgraph KC1["Kafka Cluster"] B4["Broker 1"] B5["Broker 2"] B6["Broker 3"] end subgraph D1["Destinations"] direction TB KC KC1 CC["Cloud Provider (Confluent, AWS MSK, Azure, GCP)"] end subgraph A1["Producers & Consumers"] direction LR PRODUCERS CONSUMERS end P1 & P2 -- Produce (with Metadata) --> DC -- Consume (with Metadata) --> CG1 & CG2 KC & KC1 & CC -- Messages (with Metadata) --> DC DC -- Forward (with Metadta) ---> KC & KC1 & CC SSP -- Configures --> DC classDef kafkaStyle fill:#e0f7e9,stroke:#4caf50,stroke-width:2px; class D1,SSPDC,A1 kafkaStyle; These data catalogs offer APIs that allow organizations to seamlessly integrate the data catalog with other systems, automate metadata management tasks, and build custom applications on top of the catalog’s capabilities. This flexibility is crucial for maintaining an efficient and scalable data management ecosystem. All of the above broadly captures business and technical metadata. You still need a discovery interface to query by these parameters. Ideally, you also need a self-service portal for credential vending. Data catalog also comes with potential downsides related to complexity, performance, consistency, vendor lock-in, maintenance, and learning curve. Careful evaluation of the factors is essential to determine if the use of a catalog is suitable for your specific streaming application and organizational needs. Conclusion Creating a system that helps a centralized Kafka infrastructure team to easily create, label and vend information reduces common problems and dependencies. Same benefits are passed on to the producers and consumers thus creating a scalable system/organization. --- # Chargeback for Kafka clusters URL: https://platformatory.io/blog/Chargeback-for-Kafka-clusters/ Published: 2024-07-01 Authors: Ashwin Venkatesan Categories: Kafka, Kafka Operations, Cost, Platform Engineering Introduction Kafka is the most popular streaming platform, used by more than 80% of the Fortune 100 companies. Several of these enterprises run a number of Kafka clusters, that are (usually) operated by a data / streaming platform team. One concern that emerges for such platform teams is to understand usage patterns and attribute costs to their internal customers, for both cost transparency and profit. On a cloud service such as Confluent cloud, it is relatively simple to crunch these stats out of the metrics API. But for other deployments, this can be a somewhat tough problem to solve. To begin with there are two broad archetypes for how Kafka platform teams manage. Single-tenant clusters: This is pretty simple. All costs are passed on to the tenant. Multi-tenant clusters: Every tenant is essentially being provided a topic as a service. They may have multiple producers and consumers. How do we solve for the latter in particular? Let’s explore. Kafka Operational Costs Let’s begin by figuring out the costs of running Kafka. This is not magic and will vary for each organization. The costs can be majorly differentiated into 2 categories. They are, Fixed Costs Variable Costs Fixed Costs are the costs which are incurred to keep the Kafka cluster operational. Irrespective of the usage of the Kafka cluster, there are costs associated with running a Kafka cluster. This includes, Compute unit costs - Kafka Brokers, Zookeeper, Schema Registry nodes etc. Tooling costs - Monitoring tool, SIEM tool etc. Personnel costs - Kafka administrators, support team etc. Variable Costs are the costs which are subject to vary as per the usage of the Kafka cluster. Generally, this cost will grow as the scale of the data in a organization grows. This includes, Network costs - Throughput, Max. Connections etc. Storage costs - Local Storage, Tiered storage etc. Therefore, the fully loaded cost of a Kafka cluster is pretty subjective. Charging internal customers is a little tricky. Chargeback Models When we built this Chargeback solution, we scoped for three models, Cost Centre Resource Usage Based Client Usage Based Cost Centre In this model, we charge the tenants a fraction of the total costs incurred for keeping the Kafka cluster operational. The cost-split among the tenants are determined by their usage of the Kafka cluster when compared to the total usage of the Kafka cluster. For example, assume there are 5 teams using a Kafka cluster which incurs a monthly cost of $10,000 and clocks 10 Mbps of average throughput per broker. If every team contributes to 2 Mbps of average throughput per broker, then each team will be liable to pay $2000 for Kafka services. Cost Centre model enables billing the tenants based on a fair share of the total cost. This model would fit best in scenarios where the Kafka cluster utilization is not high. Generally, the Kafka clusters are over-provisioned to account for growth over time but the cluster capacity utilization does not grow fast enough. So, splitting costs based on relative usage is fair to the customers. Resource Usage Based In this model, we charge the tenants based on their absolute usage of the Kafka resources. The Kafka resources which will be billed include, Partitions Disk Storage Broker Throughput The above mentioned resources are the ones which can be tracked easily and attributed to the operational costs. A per-unit cost for each of the above mentioned resources will need to be calculated by doing a thorough load testing on Kafka clusters. The tenants pays only for the resources utilized and not based on total costs of running the Kafka cluster. This model would fit well for scenarios with high Kafka cluster utilization. When the cluster capacity utilization is high, it is best adopt a pay-for-what-you-use strategy as the costs are generally justified because of high usage. Client Usage Based In this model, we charge the tenants based on their clients’ throughput numbers.This is similar to the Resource Usage Based model but we charge the tenants for the amount of data they send and/or read from the Kafka cluster. There are 3 sub types in this model based on who pays, Producer Pays - Only Producer clients pay for the data sent to the cluster Consumer Pays - Only Consumer clients pay for the data read from the cluster Producer and Consumer Pays - Both Producer and Consumer clients pay for the data sent and read by them respectively Client throughput is measured as bytes-per-second in the Kafka world. Therefore, a unit bytes-per-second cost for both write and read operations will need be predefined by the platform team. Unit costs can be calculated based on the observed monthly average client throughput. This model would fit well in scenarios with very high Kafka cluster utilization over long periods of time. The advantage of this model is it offers simple pricing strategy for the tenants by paying for what they send and read rather than usage of Kafka related resources. Solution Before we get to the solution, it is important to understand the considerations involved, Avoid introducing additional costs as much as possible Avoid additional development efforts as much as possible Make use of existing capabilities of Kafka Use tools which are open-source and widely used in Kafka ecosystem The solution we built uses the Kafka JMX metrics, Prometheus and Grafana. Let’s take a look at how it works. Kafka JMX metrics provides a veritable list of useful metrics which gives us a detailed information on the operations of the Kafka cluster. Some of the useful broker-side metrics include, kafka_server_brokertopicmetrics_bytesinpersec kafka_log_log_size kafka_cluster_partition_replicascount kafka_server_produce_byte_rate kafka_server_fetch_byte_rate Note: We will only be using the Broker-side metrics to do the Chargeback calculation as this is something which will be always available to the platform team managing Kafka clusters. The throughput rates, storage usage and partitions count can be inferred from the JMX metrics. But, we will need to attribute the clients or topics to a customer. This will be done by tagging the clients and/or topics to a Chargecode which will be unique for a tenant. Chargecode is a user-defined unique identifier for a tenant associated with a specific Kafka cluster. Chargecode definition will include match configuration which defines the topics and/or clients associated with that tenant in that specific Kafka cluster. Please note the Client quotas will need to predefined to capture the client specific throughput rate on the broker side. Prometheus will be used to scrape the relevant JMX metrics and re-tag them with the Chargecode as per the defined Chargecode configuration. Prometheus enables metric re-tagging through “metric_relabel_configs” definition. Grafana dashboards are created to visualize the usage and cost per Chargecodes by querying the Prometheus database. The dashboards will demonstrate the Bill per chargecode, Top N Chargecodes based on Storage, Partitions and Throughput usage etc. The dashboards are meant to enable the platform engineers in an organization to make an informed decision on managing resources and distributing costs Configurations Chargeback Model Configuration Let’s look at how to configure a Chargeback model for billing tenants in a Kafka cluster. Below is a sample configuration. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 clusters: - cluster1: cluster_name: Cluster1 # Common Key with Chargecode configuration cluster_id: 12345 # Unique cluster ID throughput_units: bytes currency_code: USD total_costs: 5000 total_capacity: throughput_tps: 1000 storage: 100000000 partitions_max: 1000 chargeback_model: cost_center # The model type chargeback_config: partition_unit_rate: 0.05 throughput_unit_rate: 0.1 storage_unit_rate: 0.001 - cluster3: cluster_name: Cluster3 cluster_id: 56789 throughput_units: bytes currency_code: USD total_costs: 5000 total_capacity: throughput_tps: 1000 storage: 100000000 partitions_max: 1000 chargeback_model: usage_based chargeback_config: partition_unit_rate: 0.05 throughput_unit_rate: 0.1 storage_unit_rate: 0.001 - cluster2: cluster_name: Cluster2 cluster_id: 98765 throughput_units: bytes currency_code: USD total_costs: 6000 total_capacity: throughput_tps: 1000 storage: 100000000 partitions_max: 1000 chargeback_model: client_usage_based chargeback_config: usage_model: producer_pays # Supported models: producer_pays, consumer_pays, producer_consumer_pays throughput_in_unit_rate: 0.15 throughput_out_unit_rate: 0.05 One Chargeback model per Kafka cluster. The fields per cluster include, cluster_name - Unique name for the cluster. This will be the common key for both model and chargecode configuration. cluster_id - Unique identifier for internal identification. throughput_units - Unit for the throughput measurement. Either “bytes” or “records”. Only “bytes” for client usage based model. currency_code - The currency unit for the bill generated total_costs - Monthly total operational cost of the Kafka cluster total_capacity - Total capacity available for that Kafka cluster throughput_tps - Allowed maximum throughput transactions (bytes or records) per second storage - Allowed maximum storage in bytes partitions_max - Allowed maximum topic partitions count chargeback_model - The model type for the Chargeback calculation chargeback_config - The per-unit rates for various resources and client throughput partition_unit_rate - Unit price for a topic partition storage_unit_rate - Unit price for each storage byte throughput_unit_rate - Unit price for each byte or record written to a Broker usage_model - The sub-model type for Client usage based model. Valid values are “producer_pays”, “consumer_pays” and “producer_consumer_pays” throughput_in_unit_rate - Unit price for each byte or record sent by a producer client. Only applicable for Client usage based model. throughput_out_unit_rate - Unit price for each byte or record read by a consumer client. Only applicable for Client usage based model. Chargecode Configuration Let’s look at how to define Chargecodes for billing tenants in a Kafka cluster. Below is a sample configuration. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 chargecodes: - chargecode_name: Chargecode1 target_cluster: Cluster1 # Joining Key match_config: - entity: client_id # Either client_id or topic match_type: prefix # Either prefix, regex or literal match_expression: "clientA_" - entity: topic match_type: literal match_expression: "important_topics" - chargecode_name: Chargecode2 target_cluster: Cluster2 match_config: - entity: client_id match_type: regex match_expression: "^clientB_.+" - entity: topic match_type: literal match_expression: "special_topics" - chargecode_name: Chargecode3 target_cluster: Cluster3 match_config: - entity: client_id match_type: literal match_expression: "clientC" - entity: topic match_type: prefix match_expression: "experimental_" Ideally, one Chargecode configuration per team per cluster. There will be one or more Chargecodes associated with a Kafka cluster. The fields per Chargecode definition include, chargecode_name - Unique name for the Chargecode. Generally, the team name will be used target_cluster - The Kafka cluster to which the Chargecode will be associated match_config - The topic or client mapping associated with the tenant entity - Entity type. Either “topic” or “client_id” match_type - Matching logic. Either “literal”, “prefix” or “regex” match_expression - The resource name to match Prometheus Configuration The defined Chargecode configuration will be converted into a “metric_relabel_configs” in the Prometheus configuration. Below is a sample Prometheus configuration for one Kafka cluster with Chargecode mapping defined under the “metric_relabel_configs” section. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 global: scrape_interval: 15s evaluation_interval: 15s rule_files: - /etc/prometheus/rules.yml scrape_configs: - job_name: 'kafka-broker' scrape_interval: 5s metrics_path: / static_configs: - targets: ['kafka1:9101','kafka2:9102','kafka3:9103'] labels: env: "dev" cluster: "Cluster1" relabel_configs: - source_labels: [__address__] target_label: hostname regex: '([^:]+)(:[0-9]+)?' replacement: '${1}' metric_relabel_configs: - source_labels: ['cluster', 'topic'] separator: '_' target_label: chargecode regex: '^Cluster1_important_topics$' replacement: 'Chargecode1' - source_labels: ['cluster', 'client_id'] separator: '_' target_label: chargecode regex: '^Clister1_clientA_(.*)$' replacement: 'Chargecode1' Additionally, we will define a custom metric called “broker_throughput_rate” which calculates the rate of the bytes produced to Kafka using the Prometheus Rules. This will be used as the throughput metric in the “Resource Usage Based” Chargeback model. 1 2 3 4 5 6 7 8 9 10 groups: ### BROKER THROUGHPUT RATE - name: record_broker_throughput_rate rules: ## Throughput related units calculation - Bytes - record: broker_throughput_rate expr: rate(kafka_server_brokertopicmetrics_bytesinpersec[5m]) labels: env: "dev" cluster: "Cluster1" Dashboards Simple and reusable Grafana dashboards are provisioned to view the usage and costs of different tenants in an organization. Let’s look at the dashboard for each of the Chargeback model. Cost Centre The following metrics are highlighted in the Cost Center model dashboard. Total cost for the Kafka cluster Current cluster capacity utilization Chargecode wise split of the cost In Amount In Percentage Top 5 Chargecodes based on usage, Throughput Partition Storage Resource Usage Based The following metrics are highlighted in the Resource Usage Based model dashboard. Total cost for the Kafka cluster Current cluster capacity utilization Total Bill based on current usage Profit/Loss value (Bill - Cost) Chargecode wise split of the usage In Amount In Percentage Top 5 Chargecodes based on usage, Throughput Partition Storage Usage bill per Chargecode for each resource type Throughput Partition Storage Usage metrics per Chargecode over time for each resource type Throughput Partition Storage Client Usage Based The following metrics are highlighted in the Client Usage Based model dashboard. Total cost for the Kafka cluster Current cluster capacity utilization Total Bill based on current usage Profit/Loss value (Bill - Cost) Chargecode wise split based on client usage In Amount In Percentage Top 5 Clients per Chargecode based on usage, Usage bill per Chargecode based on each client type Producer Consumer Usage (throughput) metrics per Chargecode over time for each client type Producer Consumer Conclusion In conclusion, implementing a Kafka chargeback solution is an effective way to attribute operational costs to various tenants in a multi-tenant Kafka environment. By leveraging the power of Kafka JMX metrics, Prometheus, and Grafana, platform teams can gain detailed insights into usage patterns and accurately distribute costs based on a variety of chargeback models. Not only does this encourage responsible usage of resources, but it also provides transparency and fairness in cost attribution. Looking ahead, we aim to refine and expand this solution, incorporating client side JMX metrics and introducing more visulaization features. --- # Interceptors for Librdkafka URL: https://platformatory.io/blog/librdkafka-interceptors/ Published: 2024-06-18 Authors: Avinash Upadhyaya Categories: Kafka, Kafka Clients, Observability Interceptors in Apache Kafka are plugins that intercept and potentially modify data that is being produced or consumed by Kafka clients. It allows the externalization of common functionality among clients without having to modify the underlying Kafka code. These interceptors can either be producer interceptors or consumer interceptors and act on a single message at a time. Interceptors hook into various stages of a produce or consume request, allowing access to the message and metadata through custom code. Interceptors play a critical role in the Apache Kafka ecosystem, with use cases around observability, logging, and simple transformations with Kafka producers and consumers. Some of the common use cases or implementations of interceptors are: Disaster Recovery: The Consumer Timestamp Interceptor is used by consumers to translate the offsets of the source cluster to the offsets in the destination cluster based on the timestamp of the message in a replicated environment. Monitoring: The monitoring interceptor allows users to monitor production and consumption of messages in the Confluent Control Center by producing telemetry to an additional topic for each message intercepted by the interceptor. Observability: One of the most common use cases for interceptors is implementing distributed tracing for Kafka clients. The Zipkin interceptor enables tracing for Kafka producers and consumers and sends these traces to Zipkin. Generic Tooling: Interceptors can also be used for general-purpose automation, such as auto-creating topics if it do not exist or verifying message integrity with signatures, etc. Data transformation: Since interceptors can also potentially modify the Kafka message, it can be used to do simple transformations on the message before producing or consuming. Building interceptors The official Apache Kafka client library produces an interface for writing producer and consumer interceptors in Java. These interceptors can be configured by setting the configuration producer.interceptor.classes for the producer interceptors and consumer.interceptor.classes for the consumer interceptors. Producer Interceptor The ProducerInterceptor interface has the following abstract methods: ProducerRecord onSend(ProducerRecord record); The onSend method is called when the producer client calls the send() method. This method has access to the complete Producer Record and can mutate the record as well before returning it to the next stage of the producer lifecycle. void onAcknowledgement(RecordMetadata metadata, Exception exception); The onAcknowledgement method is called when the broker returns the acknowledgement back to the client along with the metadata about the message, such as the message offset and partition. void close(); The close method is called when the interceptor is closed. This is typically for any cleanup or closing activity that needs to be performed. Since the ProducerInterceptor extends the interface Configurable, the following method is also available within the ProducerInterceptor: void configure(Map configs); The configure method is called when an instance of the producer interceptor is created. This is typically for instantiating any global values for the interceptor. ProducerInterceptor callbacks may be called from multiple threads. Interceptor implementation must ensure thread safety, if needed. Consumer Interceptor The Consumernterceptor interface has the following abstract methods: ConsumerRecords onConsume(ConsumerRecords records); The onConsume method is called just before the records are returned by the broker due to a poll() call from the consumer. The method has access to the consumer records returned in the batch and can potentially modify the records before returning them. void onCommit(Map offsets); The onCommit method is called when the consumer offsets are committed to the broker. It is provided with details about the topic partition and offsets that were committed. void close(); Similar to the ProducerInterceptor, the close method can be used for any cleanup or closing activity that needs to be performed when the interceptor is closed. Similar to the ProducerInterceptor, the ConsumerInterceptor also extends the interface Configurable and provides the configure method for any global instantiation. Unlike the ProducerInterceptor, the ConsumerInterceptor is called from the same thread that invokes KafkaConsumer.poll(long). These Producer and Consumer Interceptor APIs are natively only exposed in the official Java client that is part of the Apache Kafka project. However, there are multiple other client libraries out there for languages apart from Java. Librdkafka is one such popular Kafka client library written in C and C++. There are multiple other client libraries in languages such as Python, Go, C#, PHP, Rust, Haskell, and Javascript that are built using librdkafka. One would want to extend the client capabilities in these languages as well and build an interceptor. However, the interceptor API is currently only available for C language clients. In this blog, we will go over the step-by-step process of developing custom interceptors for both producers and consumers using librdkafka for C and other languages that use librdkafka. Building interceptors with librdkafka Similar to the Java library, the librdkafka library exposes various functions in C to implement a producer or consumer interceptor at various stages of the produce/consume request. For the producer interceptor, the following functions are made available: on_send on_acknowledgement For the consumer interceptor, the following functions are made available: on_consume on_commit Once these methods are implemented, a shared object file needs to be created, which can then be used by the librdkafka clients as plugins. Although the interceptors need to be written in C, they can be used by any librdkafka client in any language supported. Interceptors can be implemented along with the client application code by defining the above mentioned methods using the direct API if the client language is C or by being implemented as an external standalone plugin library that uses the direct APIs. If the client language is not C, the latter approach needs to be taken by writing the interceptor code as an external plugin in C and integrating the shared object into the client’s plugin library. Key Gotcha While the Java library for building interceptors allows for mutating the messages, the librdkafka API for interceptors does not allow modification of messages. Interceptors built with librdkafka are read-only interceptors. However, librdkafka interceptors can add, remove, or modify headers in a message. Use Case We will be building a producer and consumer interceptor to perform an audit of the message trail from producers and consumers. These interceptors will capture audit information about a message produced or consumed and send the audit details to another topic. The audit topic can be in the same cluster where the original production or consumption is happening or in a different cluster. When the message is initially produced, a correlation ID is generated and added to the message as a header. This correlation ID serves as an identifier for tracking the message across the broker and consumer(s). This allows us to build an audit trail for each individual message and track consumption or data loss. We will be demonstrating the following functionality while building the interceptors: Intercepting a message when a message is produced Intercepting the metadata when the broker sends an acknowledgement back to the producer Defining custom configuration for the interceptor Intercepting the messages before it is consumed by the consumer Initializing global configuration for an interceptor and cleaning up the configuration We will not be covering the scenarios for intercepting the offsets when committed by the consumer or when the configuration is copied instead of creating a new configuration for Kafka clients. Producer Interceptor with librdkafka Interceptor instance Each interceptor plugin has an Interceptor instance, which is created either when the plugin (interceptor) is loaded or when the configuration which was previously set is copied. We will be declaring the interceptor instance in a struct called ici: \ 1 2 3 4 struct ici { rd_kafka_conf_t *audit_producer_conf; /**< Interceptor-specific config */ char *audit_topic; }; The Interceptor instance can contain any number of members of any type. Here we are declaring an interceptor instance with 2 members: rd_kafka_conf_t *audit_producer_conf; - Used to store the producer configuration for the audit topic char *audit_topic; - Used to store the name of the audit topic conf_init When plugin.library.paths is set, the plugin’s conf initializer is called. In the initializer function, we can create and define global objects and functions for the interceptor. In the init function, we will instantiate the Interceptor instance ici along with defining the interceptor methods to be called for various interceptor lifecycle stages, such as new interceptor, configuration set, configuration copied (duplicated) and configuration destroyed. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 static void conf_init0(rd_kafka_conf_t *conf) { struct ici *ici; ici = calloc(1, sizeof(*ici)); ici->audit_producer_conf = rd_kafka_conf_new(); rd_kafka_conf_interceptor_add_on_new(conf, __FILE__, on_new, ici); rd_kafka_conf_interceptor_add_on_conf_set(conf, __FILE__, on_conf_set, ici); rd_kafka_conf_interceptor_add_on_conf_destroy(conf, __FILE__, on_conf_destroy, ici); } rd_kafka_resp_err_t conf_init(rd_kafka_conf_t *conf, void **plug_opaquep, char *errstr, size_t errstr_size){ conf_init0(conf); return RD_KAFKA_RESP_ERR_NO_ERROR; } Here, we are initializing the ici object along with instantiating the members of the ici struct. Along with that, we are defining the methods for when a new interceptor is created, when the configuration is set, and when the configuration is destroyed, i.e., when the interceptor is destroyed. The conf_init method has access to the complete client configuration, which is passed to the on_new, on_conf_set and on_conf_destroy methods. on_new The on_new method is called when rd_kafka_new() or equivalent methods in other languages are called. We will use this method to set up the interceptor. 1 2 3 4 5 6 7 8 9 10 11 12 static rd_kafka_resp_err_t on_new(rd_kafka_t *rk, const rd_kafka_conf_t *conf, void *ic_opaque, char *errstr, size_t errstr_size) { struct ici *ici = ic_opaque; rd_kafka_interceptor_add_on_send(rk, __FILE__, on_send, ici); rd_kafka_interceptor_add_on_acknowledgement(rk, __FILE__, on_acknowledgement, ici); return RD_KAFKA_RESP_ERR_NO_ERROR; } Here, we define the methods for the 2 important events of a producer interceptor: on_send and on_acknowledgement. Both these methods will have access to the interceptor object. on_conf_set The on_conf_set method is called for each configuration set by the kafka client. The method should return one of RD_KAFKA_CONF_OK, RD_KAFKA_CONF_INVALID or RD_KAFKA_CONF_UNKNOWN. If the configuration is a configuration that is expected by the interceptor and not necessary for the client, the method should return RD_KAFKA_CONF_OK. If the method returns RD_KAFKA_CONF_UNKNOWN, librdkafka will check if the configuration is valid with other interceptors and, finally, with the list of other configurations that librdkafka recognizes. Returning RD_KAFKA_CONF_INVALID will cause the client to fail. This should only be returned if the configuration name is expected by the interceptor but the value is not as expected. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 static rd_kafka_conf_res_t on_conf_set(rd_kafka_conf_t *conf, const char *name, const char *val, char *errstr, size_t errstr_size, void *ic_opaque) { struct ici *ici = ic_opaque; int level = 3; const char *prefix = "audit."; if (strcmp(name, "audit.topic")==0) { ici->audit_topic = strdup(val); return RD_KAFKA_CONF_OK; } if (strncmp(prefix, name, strlen(prefix)) == 0) { size_t prop_len = strlen(name)-strlen(prefix); char *prop = (char *)malloc((prop_len + 1) * sizeof(char)); strncpy(prop, name+strlen(prefix), prop_len); rd_kafka_conf_set(ici->audit_producer_conf, prop, val, errstr, errstr_size); return RD_KAFKA_CONF_OK; } else { /* UNKNOWN makes the conf_set() call continue with * other interceptors and finally the librdkafka properties. */ return RD_KAFKA_CONF_UNKNOWN; } return RD_KAFKA_CONF_UNKNOWN; } Here, we are checking if the configuration name is “audit.topic” or if it starts with “audit.” before returning RD_KAFKA_CONF_UNKNOWN if it does not match the criteria. If the criteria is met, the interceptor instance ici is updated with the values. on_conf_destroy The on_conf_destroy method is called when rd_kafka_conf_destroy() or equivalent methods in other languages are called. We will use this method to clean up and free memory for any objects that were created as part of the interceptor. \ 1 2 3 4 5 6 7 8 9 10 11 12 13 static void ici_destroy(struct ici *ici) { if (ici->audit_producer_conf) free(ici->audit_producer_conf); if (ici->audit_topic) free(ici->audit_topic); free(ici); } static rd_kafka_resp_err_t on_conf_destroy(void *ic_opaque) { struct ici *ici = ic_opaque; ici_destroy(ici); return RD_KAFKA_RESP_ERR_NO_ERROR; } on_send The on_send method is called when the client application code calls the produce() method. The on_send method has access to the top level object rd_kafka_t and the message produced rd_kafka_message_t. The method also has access to the interceptor instance ici for any global variables. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 static rd_kafka_resp_err_t on_send(rd_kafka_t *rk, rd_kafka_message_t *rkmessage, void *ic_opaque) { struct ici *ici = ic_opaque; if (!rkmessage || !rkmessage->payload) { fprintf(stderr, "No message payload to process.\n"); return RD_KAFKA_RESP_ERR_NO_ERROR; } char *correlation_id = generate_correlation_id(); rd_kafka_headers_t *headers; rd_kafka_message_headers(rkmessage, &headers); if (!headers) { headers = rd_kafka_headers_new(8); } rd_kafka_header_add(headers, "correlation_id", -1, correlation_id, -1); rd_kafka_message_set_headers(rkmessage, headers); free(correlation_id); return RD_KAFKA_RESP_ERR_NO_ERROR; } We are fetching the message headers, and if there are no message headers, we are initializing it. Finally, we set the header correlation_id with the random UUID generated. on_acknowledgement The on_acknowledgement method is called when the broker returns the message acknowledgement with the message metadata, such as offset and partition of the message in the broker, along with the complete message produced. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 rd_kafka_resp_err_t on_acknowledgement(rd_kafka_t *rk, rd_kafka_message_t *rkmessage, void *ic_opaque) { struct ici *ici = ic_opaque; const void *correlation_id; size_t correlation_id_size; const rd_kafka_conf_t *producer_conf = rd_kafka_conf(rk); char client_id[512]; size_t client_id_size = sizeof(client_id); rd_kafka_conf_get(producer_conf, "client.id", client_id, &client_id_size); const char *topic = rd_kafka_topic_name(rkmessage->rkt); rd_kafka_headers_t *headers; rd_kafka_message_headers(rkmessage, &headers); if (!headers) { headers = rd_kafka_headers_new(8); } if (rd_kafka_header_get(headers, 0, "correlation_id", &correlation_id, &correlation_id_size) == RD_KAFKA_RESP_ERR_NO_ERROR) { time_t rawtime; struct tm * timeinfo; time ( &rawtime ); timeinfo = localtime ( &rawtime ); // Send the message to an audit topic using a separate producer instance rd_kafka_t *audit_rk = init_audit_producer(ici); if (audit_rk) { char *json_payload = generate_json_payload(asctime(timeinfo), correlation_id, topic, client_id, rkmessage->partition, rkmessage->offset); rd_kafka_producev( audit_rk, RD_KAFKA_V_TOPIC(ici->audit_topic), RD_KAFKA_V_MSGFLAGS(RD_KAFKA_MSG_F_COPY), RD_KAFKA_V_VALUE(json_payload, strlen(json_payload)), RD_KAFKA_V_KEY(correlation_id, correlation_id_size), RD_KAFKA_V_END ); rd_kafka_flush(audit_rk, 10000); // Wait for messages to be delivered rd_kafka_destroy(audit_rk); // Clean up the audit producer } } return RD_KAFKA_RESP_ERR_NO_ERROR; } Using the top-level rd_kafka_t object, we can fetch the producer configuration, such as the client ID, and using the rd_kafka_message_t object, we can fetch the headers for the correlation ID. We will instantiate a producer using the audit producer configuration stored in the interceptor object ici. Finally, we will produce the audit JSON message to the audit topic before cleaning up the resources created. Helper functions There are 2 helper functions for generating a random UUID, which will be used as the correlation id and for generating a JSON payload for the audit message. For the sake of brevity, we will omit the code in this blog but the complete code can be found on Github. 1 2 3 4 5 6 7 8 char *generate_correlation_id() { // Omitted for brevity } char *generate_json_payload(const char *timestamp, const char *correlation_id, const char *topic, const char *client, int partition, long offset) { // Omitted for brevity } Error Handling Every method in the librdkafka interceptor API expects an error code to be returned. RD_KAFKA_RESP_ERR_NO_ERROR is to be returned if there are no errors in the method. The full list of error codes can be found in the librdkafka source code. Compiling We will need librdkafka, jannson and libuuid installed in the environment where the interceptor will be compiled. For ubuntu: 1 sudo apt install librdkafka-dev libjansson-dev uuid-dev GCC will be used to build a shared object file after compiling the C interceptor code. 1 gcc -o audit_producer_interceptor.so -shared -fPIC audit_producer_interceptor.c -lrdkafka -ljansson -luuid Testing Once the shared object is built, we can plug it into the client application code. To test the interceptor, we will be using Python with the confluent-kafka-python library, which is a wrapper for librdkafka in Python. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 from confluent_kafka import Producer import random import os conf = { 'bootstrap.servers': 'localhost:9092', 'plugin.library.paths': os.getcwd()+'/audit_producer_interceptor.so', # Ensure correct path 'client.id': 'demo-producer', 'audit.bootstrap.servers': os.environ.get('AUDIT_BOOTSTRAP_SERVER'), 'audit.sasl.mechanism': 'PLAIN', 'audit.security.protocol': 'SASL_SSL', 'audit.sasl.username': os.environ.get('AUDIT_SASL_USERNAME'), 'audit.sasl.password': os.environ.get('AUDIT_SASL_PASSWORD'), 'audit.topic': 'audit_topic', } def main(): producer = Producer(conf) def delivery_report(err, msg): if err is not None: print(f"Message delivery failed: {err}") else: print(f"Message delivered to {msg.topic()} [{msg.partition()}]") # Produce a message producer.produce('test_topic', "Hello world! Here's a random number - "+str(random.randint(1, 2100)), callback=delivery_report) if __name__ == "__main__": main() Notice the plugin.library.paths which is set to the path of the shared object previously compiled. The shared object can also be placed in /usr/local/lib or /usr/lib based on the librdkafka version and the plugin.library.path can be set to just the name of the shared object - audit_producer_interceptor. The audit producer and topic configuration is defined with the audit. prefix. It can be the same Kafka cluster or an entirely different cluster. Once we run the python application, we should be able to consume from the audit topic. An example of the message from the audit topic - 1 2 3 4 5 6 7 8 9 { "timestamp": "Fri Jun 7 13:23:43 2024", "correlation_id": "c0613861-f1a9-47f0-9b92-09a2346fe250", "action": "produce", "topic": "test_topic", "client": "ksb-demo-producer", "partition": 0, "offset": 13 } Complete code for the producer interceptor can be found on GitHub along with the code for the test client. Consumer Interceptor with librdkafka A consumer interceptor can be built similar to the producer interceptor with the same set of APIs except for the consumer specific hooks such as on_consume and on_commit instead of on_send and on_acknowledgement. A consumer interceptor has an Interceptor instance, which was defined as ici in the producer interceptor. The interceptor’s lifecycle starts with the conf_init method, where we define the on_new, on_conf_set and on_conf_destroy methods, similar to the producer interceptor. In the on_new method, we define the methods for on_consume and on_commit. on_consume The on_consume method is called just before the consumer client receives the messages fetched through the rd_kafka_consumer_poll() method or equivalent method in other client language libraries. The on_consume method is called for each individual message, even if the consumer fetches multiple message for each poll. The on_consume method has access to the top level object rd_kafka_t and the message produced, rd_kafka_message_t. The method also has access to the interceptor instance ici for any global variables. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 static rd_kafka_resp_err_t on_consume(rd_kafka_t *rk, rd_kafka_message_t *rkmessage, void *ic_opaque) { struct ici *ici = ic_opaque; if (!rkmessage || !rkmessage->payload) { printf("No message payload to process.\n"); return RD_KAFKA_RESP_ERR_NO_ERROR; } rd_kafka_headers_t *headers = NULL; if (rd_kafka_message_headers(rkmessage, &headers) == RD_KAFKA_RESP_ERR_NO_ERROR) { const void *correlation_id; size_t correlation_id_size; const rd_kafka_conf_t *consumer_conf = rd_kafka_conf(rk); char group_id[512]; size_t group_id_size = sizeof(group_id); rd_kafka_conf_get(consumer_conf, "group.id", group_id, &group_id_size); const char *topic = rd_kafka_topic_name(rkmessage->rkt); if (rd_kafka_header_get(headers, 0, "correlation_id", &correlation_id, &correlation_id_size) == RD_KAFKA_RESP_ERR_NO_ERROR) { time_t rawtime; struct tm * timeinfo; time ( &rawtime ); timeinfo = localtime ( &rawtime ); rd_kafka_t *audit_rk = init_audit_producer(ici); if (audit_rk) { char *json_payload = generate_json_payload(asctime(timeinfo), correlation_id, topic, group_id, rkmessage->partition, rkmessage->offset); rd_kafka_producev( audit_rk, RD_KAFKA_V_TOPIC(ici->audit_topic), RD_KAFKA_V_MSGFLAGS(RD_KAFKA_MSG_F_COPY), RD_KAFKA_V_VALUE(json_payload, strlen(json_payload)), RD_KAFKA_V_KEY(correlation_id, correlation_id_size), RD_KAFKA_V_END ); rd_kafka_flush(audit_rk, 10000); // Wait for messages to be delivered rd_kafka_destroy(audit_rk); // Clean up the audit producer } } else { fprintf(stderr, "AuditInterceptor: Correlation ID header missing.\n"); } } else { fprintf(stderr, "AuditInterceptor: No headers found.\n"); } return RD_KAFKA_RESP_ERR_NO_ERROR; } Similar to the producer interceptor’s on_acknowledgement method, we instantiate a producer for the audit message and send a JSON message to the audit topic. on_commit The on_commit method is called when the offsets are committed by the consumer. The on_commit method has access to the top-level object rd_kafka_t and the offsets that were committed. The method also receives the interceptor instance and any error that was returned during the offset commit. Since the on_commit method does not have the message and the headers of the message, we will not be able to generate an audit message. The audit message requires the correlation ID that is part of the message header. The example will not include an implementation of the on_commit method. Compiling Similar to the producer interceptor, we will be using gcc to compile the interceptor and generate a shared object. 1 gcc -o audit_consumer_interceptor.so -shared -fPIC audit_consumer_interceptor.c -lrdkafka -ljansson Testing We can use the following python code to test the consumer interceptor - 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 from confluent_kafka import Consumer import os conf = { 'bootstrap.servers': 'localhost:9092', 'group.id': 'ksb-demo-group', 'auto.offset.reset': 'earliest', 'plugin.library.paths': os.getcwd()+'/audit_consumer_interceptor', # Ensure correct path 'audit.bootstrap.servers': os.environ.get('AUDIT_BOOTSTRAP_SERVER'), 'audit.sasl.mechanism': 'PLAIN', 'audit.security.protocol': 'SASL_SSL', 'audit.sasl.username': os.environ.get('AUDIT_SASL_USERNAME'), 'audit.sasl.password': os.environ.get('AUDIT_SASL_PASSWORD'), 'audit.topic': 'audit_topic', } consumer = Consumer(conf) consumer.subscribe(['test_topic']) try: while True: msg = consumer.poll(timeout=1.0) if msg is None: continue if msg.error(): print("Consumer error: {}".format(msg.error())) continue print(f'Received message: {msg.value().decode("utf-8")}') finally: consumer.close() The interceptor is declared using the plugin.library.paths configuration. Once we run the application, the interceptor will produce a message to the audit topic. Conclusion Although not every client language library built using librdkafka supports building interceptors natively, we can work around it by building interceptors in C and plugging it into the respective client language code using the configuration plugin.library.paths. Interceptors drive various use cases as mentioned earlier but should only be used to perform non-blocking operations, especially in the on_send and on_consume methods since these can contribute to the latency experienced by the client application. The complete source code and the test scripts can be found on GitHub. The librdkafka test cases for interceptors are also an excellent source for examples of writing interceptors for librdkafka. --- # Flink Deployment Patterns URL: https://platformatory.io/blog/Flink-Deployment-Patterns/ Published: 2024-03-13 Authors: Ashwin Venkatesan, Avinash Upadhyaya Categories: Apache Flink, Stream Processing, Kubernetes, Platform Engineering Introduction Apache Flink is an open-source, unified stream-processing and batch-processing framework designed for high-performance, scalability, and accuracy. Apache Flink has a very large and vibrant community with 450+ contributors and 15500+ commits, supported by companies like Apple and Alibaba, that helps to ensure continual innovation. It powers stream processing platforms at many companies, including digital natives like Uber, Netflix, and Linkedin, as well as successful enterprises like ING, Goldman Sachs, and Comcast. Apache Flink supports high throughput and low event latency at the same time, fault-tolerance with exactly-once processing guarantees, event time and out of order processing etc. It has elegant and fluent APIs in Java, Scala and Python. It has libraries for Graph processing (batch), Machine Learning (batch), and Complex Event Processing (streaming). Flink is the de facto industry standard for stream processing Cluster Framework Apache Flink jobs run on clusters, which are composed of two types of nodes: TaskManagers and JobManagers. While clusters typically consists of multiple TaskManagers, only reason to run multiple JobManagers is high availability. The jobs are submitted to JobManager by FlinkClient, that compiles user application into dataflow graph which is understandable by JobManager. JobManager then coordinates job execution: it splits the parallel units of a job to TaskManagers, manages heartbeats, triggers checkpoints, reacts to failures and much more. JobManager supports multiple job submission modes such as, Application mode Session mode Application mode This mode creates one cluster per submitted application. A dedicated JobManager is started for submitting the job. The JobManager will only execute this job, then exit. The Flink application runs on the JobManager. With this architecture, the Application Mode provides the resource isolation and load balancing guarantees at the granularity of a whole application. Session mode Session mode assumes an already running cluster and uses the resources of that cluster to execute any submitted application. Applications executed in the same (session) cluster use, and consequently compete for, the same resources. This has the advantage that you do not pay the resource overhead of spinning up a full cluster for every submitted job. Deployment Patterns Flink is a versatile framework, supporting many different deployment patterns in a mix and match fashion. The available deployment patterns include, Standalone YARN Kubernetes Cloud Standalone The standalone mode is the most barebone way of deploying Flink. The Flink services such as JobManager and TaskManager are just launched as processes on the operating system. Flink runs on all UNIX like systems e.g. Linux, Mac OS X and Cygwin. Flink requires Java 1.8.x or higher installed. In Production environments, the Flink clusters have to be deployed for High-availability(HA) to ensure smooth processing. To enable HA for a standalone cluster, you have to use the ZooKeeper HA services. Flink leverages ZooKeeper for distributed coordination between all running JobManager instances. For more details on the deployment steps, please refer to this link. Standalone deployment in Flink offers simplicity and flexibility, making it suitable for various use cases ranging from small-scale development and testing environments to large-scale production deployments. However, it also requires manual management of resources and may not provide the same level of resource isolation and multi-tenancy capabilities as other deployment options like YARN or Kubernetes. YARN YARN is a popular resource manager for running Hadoop jobs and other data processing applications such as MapReduce, Spark, Storm and Flink, among others. YARN (Yet Another Resource Manager) was born out of the idea to separate the concerns of resource management and job scheduling/monitoring. YARN achieves this with two components - Resource Manager and Node Manager. The Resource Manager accepts jobs from the client and schedules them to be run on the Node Manager. The Node Manager runs the application by creating multiple containers. Apache Flink can be deployed using YARN by creating Flink’s JobManager and TaskManager in such containers. This allows to dynamically allocate and de-allocate TaskManager resources based on the job running. YARN allows deploying Flink applications in all deployment modes supported by Apache Flink including the deprecated Per-Job mode. Flink applications can be deployed in the Application Mode or in the Session Mode. YARN also allows submitting Flink jobs using the SQL client. This makes it an attractive choice for deploying Apache Flink if there are existing YARN clusters running or if there are plans to use other data processing systems in conjunction with Flink, allowing them to be deployed together. YARN can be scaled up or down depending on the load and provides token based security with Kerberos authentication. YARN is not particularly a great choice if you are not already in the Apache Hadoop ecosystem since there is a steep learning curve and requires expertise managing the additional configurations and settings, which can be difficult for those who are not familiar with YARN. Kubernetes Kubernetes has grown to be the de-facto orchestrator for deploying Cloud Native workloads. Apache Flink comes with a native integration with Kubernetes to deploy Flink. Similar to YARN, the native Kubernetes integration allows to dynamically allocate and de-allocate TaskManager resources based on the job running. Apart from the native integration, there are multiple Kubernetes Operators that allow creation of Flink Jobs declaratively. The native Kubernetes integration allows running Flink jobs without the hassle of writing YAML files and abstracting the Kubernetes complexity while providing the benefits of Kubernetes such as auto-healing and resource orchestration. This can be a good first step towards running Flink Jobs in Kubernetes while using the same clients for submitting Flink Jobs. Flink also offers High Availability(HA) while deploying using the native Kubernetes integration. There are multiple open source Kubernetes Operators for Flink such as the official Apache Flink Operator, Flinkk8soperator by Lyft and the Flink on Kubernetes operator by Spotify. These operators allow declaratively defining the Flink cluster and creating Flink Jobs using a Custom Resource in Kubernetes. This implies, Flink Jobs can be natively managed using Kubernetes clients and operational governance can be implemented with GitOps. While there are several advantages to deploying Flink on Kubernetes such as high availability and scalability, it requires expertise in running and maintaining a Kubernetes cluster along with ensuring the Flink applications are fault tolerant with appropriate recovery mechanisms. Cloud Fully managed services abstract away much of the complexity involved in deploying and managing Apache Flink clusters. Users don’t need to worry about infrastructure provisioning, cluster configuration, or software updates, as these tasks are handled by the managed service provider. Deploy highly available and durable applications with Multi-AZ deployments and APIs for application lifecycle management. Managed services provide built-in monitoring and logging capabilities, allowing users to easily track the performance and health of their Flink applications. It also offers enhanced security features, such as encryption, access controls, and compliance certifications. Finally, managed services integrate seamlessly with other cloud services and data processing tools, allowing users to build end-to-end data pipelines more easily. Challenges in self-managed Flink cluster While self managing a Flink cluster offers greater flexibility in terms of the APIs supported or the connectors, it comes with the operational hazard of maintaining a platform. As with any self managed system, self managing Flink would imply being responsible for the security of the system and scaling the system. While self managing the Flink clusters, the focus of the team would be more towards managing infrastructure than creating streaming applications. Using a managed service would allow to offload operational burdens to a provider. Certain managed services handle check-pointing as well, allowing the developer to purely focus on the streaming logic. How Confluent’s fully managed Flink service help developers? Kafka has become the de facto standard for messaging system and similarly Flink is the de facto industry standard for stream processing. The Confluent offering for Apache Kafka and Apache Flink goes hand-in-hand to facilitate a rich-environment for real-time stream processing. Confluent Cloud provides a cloud-native, serverless service for Flink that enables simple, scalable, and secure stream processing that integrates seamlessly with Apache Kafka. Your Kafka topics appear automatically as queryable Flink tables, with schemas and metadata attached by Confluent Cloud. Confluent Cloud for Apache Flink is a cloud-native service in a truest sense. Confluent’s fully managed Flink service enables you to: Easily filter, join, and enrich your data streams with Flink Enable high-performance and efficient stream processing at any scale, without the complexities of managing infrastructure Experience Kafka and Flink as a unified platform, with fully integrated monitoring, security, and governance Confluent Cloud for Apache Flink let you focus fully on your business logic, encapsulated in Flink SQL statements, and Confluent Cloud takes care of what’s needed to run them in a secure, resource-efficient and fault-tolerant manner. Fully Managed Confluent Cloud always uses the latest Flink version. Any security patches to Flink runtime are applied seamlessly and automatically Auto-scaling Flink SQL statements on Confluent Cloud are monitored continuously and auto-scaled to keep up with the throughput rate of their input topics. Usage-based billing You pay only for what you use, not what you provision. Flink compute in Confluent Cloud is elastic: once you stop using the compute resources, they are deallocated, and you no longer pay for them. Metadata Sync Kafka topics and schemas are always in sync with Flink, simplifying how you can process your data. Any topic created in Kafka is visible directly as a table in Flink, and any table created in Flink is visible as a topic in Kafka Observability Confluent Cloud provides you with a curated set of metrics, exposing them through Confluent’s existing metrics API. Confluent Cloud provides first-class integrations with New Relic, Datadog, Grafana Cloud, and Dynatrace Security Confluent Cloud for Apache Flink has a deep integration with Role-Based Access Control (RBAC), ensuring that you can easily access and process the data that you have access to, and no other data. Cloud Availability Confluent Cloud for Apache Flink is available on AWS, Azure, and GCP. Refer to this link for the supported region wise list. Learn more about Confluent’s cloud-native,serverless Apache Flink® service—now generally available on AWS, Azure, and Google Cloud. Conclusion Apache Flink stands as a robust and versatile framework for real-time stream processing and batch processing with its fault tolerance, high throughput, low-latency processing capabilities, and seamless integration with various data sources. Managing Flink clusters involves dealing with infrastructure concerns such as deployment, scaling, and maintenance. By outsourcing this responsibility to managed services or cloud providers, businesses can redirect their focus towards their core competencies, such as developing innovative data processing pipelines tailored to their specific business needs. Confluent Cloud for Apache Flink enables businesses to build efficient and tailored data processing workflows without any infrastructure management hassles. It also seamlessly integrates with Confluent Kafka and Schema Registry. References https://nightlies.apache.org/flink/flink-docs-release-1.18/docs/deployment/overview/ https://docs.confluent.io/cloud/current/flink/index.html#stream-processing-with-af-long --- # End-To-End Streaming Pipeline using KSQLDB and Kafka Connect URL: https://platformatory.io/blog/End-To-End-Streaming-Pipeline-using-KSQLDB-and-Kafka-Connect/ Published: 2023-06-28 Authors: Ashwin Venkatesan Categories: Stream Processing, Kafka, Kafka Connect, ksqlDB, Confluent Cloud Introduction KSQLDB and Kafka Connect are two technologies that are commonly used together in the Apache Kafka ecosystem for stream processing and data integration. Kafka Connect is a framework for building and running connectors between Kafka and other data systems, such as databases, file systems, and message queues. Connectors are plugins that are responsible for moving data between Kafka and external systems, either in a one-way or a two-way fashion. Kafka Connect provides a scalable and fault-tolerant way of integrating data between different systems. KSQLDB, on the other hand, is a streaming SQL engine for Apache Kafka that allows developers to write SQL queries on top of Kafka streams. KSQLDB makes it easy to perform stream processing tasks, such as filtering, aggregating, and joining streams of data in real-time. KSQLDB also provides support for stream-table joins, which allows developers to join a Kafka stream with a Kafka table. KSQLDB and Kafka Connect in Confluent Architecture Confluent Cloud is a fully managed cloud-native event streaming platform that provides a scalable and secure way to build real-time streaming applications in the cloud. It offers connectors that are pre-configured, fully managed, and can be deployed with just a few clicks in the Confluent Cloud Console or via the Confluent Cloud CLI. It also provides a user-friendly web interface for managing and executing queries in KSQLDB, as well as an API for programmatic access. Confluent Platform, on the other hand, is a self-managed version of the Confluent stack that can be deployed on-premises or in the cloud. Confluent Platform provides additional features such as multi-datacenter replication, advanced security options, and enhanced monitoring and management capabilities. The Kafka Connect and KSQLDB servers are self managed and available through HTTP API for use. The required connectors need to be manually loaded into Kafka Connect server and configured. In summary, both Confluent Cloud and Confluent Platform provide Kafka clusters, Kafka Connect, and KSQLDB, but Confluent Platform offers additional features and customization options for those who require more control over their Kafka infrastructure. Managed vs Self-hosted Operation Cost Confluent Cloud requires a Kafka cluster for using Connectors and KSQLDB. It primarily offers three types of clusters, Basic, Standard and Dedicated. The pricing are as follows, Basic - $0 per hour Standard - $1.50 per hour Dedicated - Cost based on number of CKUs (Confluent Unit for Kafka) The connector deployments are priced based on the connector task instance and the amount of data being transferred. Please look at this link for more details. KSQLDB servers are priced as $0.23 per CSU hour. A CSU (Confluent Streaming Unit) is the compute unit for fully managed ksqlDB. Clusters can be configured with 1, 2, 4, 8, or 12 CSUs based upon the workload. In Confluent Platform, both Kafka Connect cluster and KSQLDB server are available under Confluent Community license and does not have any licensing cost. The components have its own requirement on Memory and CPU based on the expected usage, so the cost of setting up the infrastructure locally or in cloud exists. The commercial connectors still needs to be licensed before use in Kafka Connect. Deployment Options Kafka Connect and KSQL clusters can be deployed in Confluent Cloud using any of the following methods, Confluent Cloud console Confluent CLI Confluent Terraform provider Confluent Pulumi provider Both Terraform and Pulumi providers automate deployments and offer version control when used in conjunction with Github, Gitlab etc. Kafka Connect and KSQL clusters can be deployed in Confluent Platform using any of the following methods, Manual Confluent Package Installation Docker images Ansible playbook for Confluent Platform Confluent for Kubernetes Ansible playbooks offer a simple automated way to deploy Confluent Platform components in multiple machines. Confluent for Kubernetes (CFK) is a cloud-native control plane for deploying and managing Confluent in your private cloud environment. Based on this execution model and depending on how we want to run our queries, currently, ksqlDB provides two deployment options. **Headless ksqlDB deployments -** In the headless mode, you write all of your queries in a SQL file, and then start ksqlDB server instances with this file as an argument. Confluent Platform supports this type of KSQL deployment. **Interactive ksqlDB deployments -** In interactive mode, you interact with the ksqlDB servers through a REST API either directly via your favorite REST clients, through ksqlDB CLI or through Confluent Control Center. Both Confluent Cloud and Confluent Platform support this type of KSQL deployment. Multi-Tenancy Kafka Connect and KSQLDB does not natively support multi-tenancy in both Confluent Cloud and Confluent Platform, but it is possible to implement a multi-tenancy model. Deploy multiple Kafka Connect and KSQLDB clusters, each dedicated to a specific tenant or application. Each Kafka Connect cluster can be configured with its own set of connectors and configurations, and can run on a separate set of hardware resources. This will lead to resource isolation in terms of connector tasks and scaling resources based on application requirements. Similarly, each KSQLDB cluster can be used to host one application or use case with dedicated resources. Deploying multiple applications in a single KSQL cluster can lead to resource issues because of an application being greedy for resources. It also makes it easier to reason about scaling, failovers, replication and resource utilization. Future KSQLDB provides the ability to define and use user-defined functions (UDFs) in SQL queries. UDFs allow developers to extend the functionality of KSQLDB by defining their own custom functions that can be used in SQL expressions. As of now, the support for KSQL UDF is only present in Confluent Platform (self-hosted) deployments. Support for KSQL UDF might be introduced for Confluent Cloud as well. Recently, Confluent acquired Immerok which is a contributor to the open source stream processing application technology Apache Flink. So, there might be a support released for FlinkSQL in KSQLDB in the future. End-To-End Streaming Pipeline We will now build a sample end-to-end streaming pipeline using Kafka Connect and KSQLDB in both Confluent Cloud and Confluent Platform. Both the scenarios will be using Kafka Cluster deployed in Confluent Cloud for Kafka Topic storage. So, please create a Basic Kafka cluster in Confluent Cloud by registering in this link. This demo will also require Schema registry cluster for storing Avro schema of the record values. You can create a Schema registry cluster in the Confluent Cloud by enabling the Streams Governance Essentials Package. You can follow this link for more information. Create a Kafka cluster API Key in your Confluent cloud account from under the Cluster Overview section, so that the connectors and KSQLDB can access data from Kafka topics during stream processing. Following are the details of the streaming pipeline, Deploy a Datagen source connector to inject “Shoe Clickstream” data into the input topic Create a KSQL Stream for the input topic Create a aggregated KSQL table to calculate the total view time per product per user for every 1 minute time window and write it to a output topic. Sink the data from output topic to a Postgres database using the JDBC Sink Connector. The connectors used in this demo will be deployed using SQL queries in KSQL in both Confluent Cloud and Confluent Platform deployments. Confluent Cloud We will use the Confluent Cloud console to create KSQL cluster but this can be achieved through any of the above mentioned deployment options for Confluent Cloud. Create a KSQL cluster in your Confluent Cloud account with Global access (only for testing). Once, the KSQL cluster is provisioned. we will create a Datagen source connector to push data into the input topic clickstream_cloud_input. We will use the SHOE_CLICKSTREAM quick start data generator and set the data type as AVRO for the record values. The Kafka API key pair created above will be used to create the input topic and write data into it. 1 2 3 4 5 6 7 8 9 CREATE SOURCE CONNECTOR "ClickstreamDataGenSourceConnector" WITH ( "connector.class"='DatagenSource', "kafka.api.key"='${KAFKA_API_KEY}', "kafka.api.secret"='${KAFKA_API_SECRET}', "kafka.topic"='clickstream_cloud_input', "output.data.format"='AVRO', "quickstart"='SHOE_CLICKSTREAM', "tasks.max"='1' ); Once the Datagen source connector is successfully deployed, we should be able to see the generated records for the input topic in the Confluent Cloud UI. Let’s create a Kafka stream called CLICKSTREAM_CLOUD_STREAM from this input topic clickstream_cloud_input for further processing. We will mention the timestamp field in the message value to be used for windowing by using the timestamp variable under the WITH clause. 1 2 3 4 5 CREATE OR REPLACE STREAM CLICKSTREAM_CLOUD_STREAM (PRODUCT_ID VARCHAR, USER_ID VARCHAR, VIEW_TIME INT, PAGE_URL VARCHAR, IP VARCHAR, TS BIGINT) WITH (kafka_topic='clickstream_cloud_input', partitions=1, value_format='AVRO', timestamp='TS'); Create a Kafka Table called USER_PRODUCT_VIEWTIME backed by a Kafka topic clickstream_cloud_output which aggregates the total view time per product per user for every 1 minute time window. The aggregated sum of the view time is saved as TOTAL_VIEW_TIME field in the table. 1 2 3 4 5 6 7 8 9 CREATE OR REPLACE TABLE USER_PRODUCT_VIEWTIME WITH (kafka_topic='clickstream_cloud_output', partitions=1, key_format='AVRO', value_format='AVRO') AS SELECT USER_ID, PRODUCT_ID, AS_VALUE(USER_ID) AS USERID, AS_VALUE(PRODUCT_ID) AS PRODUCTID, SUM(VIEW_TIME) AS TOTAL_VIEW_TIME, WINDOWEND AS END_TIME, WINDOWSTART AS START_TIME FROM CLICKSTREAM_CLOUD_STREAM WINDOW TUMBLING (SIZE 1 MINUTES, RETENTION 7 DAYS) GROUP BY USER_ID, PRODUCT_ID; Following, is a sample view of the records received by the ouput topic clickstream_cloud_output Let’s create a Postgres JDBC Sink connector which writes the aggregated values from the output topic to a remote Postgres database. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 CREATE SINK CONNECTOR "PostgresClickstreamSinkConnector" WITH ( 'connector.class' = 'PostgresSink', 'kafka.api.key' = '${KAFKA_API_KEY}', 'kafka.api.secret' = '${KAFKA_API_SECRET}', 'connection.host' = 'postgresql-119942-0.cloudclusters.net', 'connection.port' = '10091', 'connection.user' = '${POSTGRES_USER}', 'connection.password' = '${POSTGRES_PASSWORD}', 'db.name' = 'default', 'topics' = 'clickstream_cloud_output', 'input.data.format' = 'AVRO', 'input.key.format' = 'AVRO', 'delete.enabled' = 'false', 'ssl.mode' = 'prefer', 'insert.mode' = 'UPSERT', 'table.name.format' = 'clickstream_user_product_viewtime', 'db.timezone' = 'UTC', 'pk.mode' = 'record_value', 'pk.fields' = 'USERID,PRODUCTID', 'auto.create' = 'true', 'auto.evolve' = 'true', 'quote.sql.identifiers' = 'ALWAYS', 'batch.sizes' = '3000', 'tasks.max' = '1' ); Here is the sample view of the clickstream_user_product_viewtime table in the Postgres database post the sink connector deployment. Confluent Platform For Confluent Platform, we will use the Kafka Connect and KSQLDB docker images to deploy the respective clusters in a hybrid mode i.e. use the Kafka cluster in Confluent Cloud for Kafka topics. We will be deploying the streaming pipeline using the KSQL interactive mode by using KSQLDB CLI image to connect to the KSQLDB cluster. We will need to supply the credentials of the Schema Registry, which can be obtained from Confluent Cloud, in case of using Avro, JsonSchema or Protobuf formats for record key or value. The Kafka Connect image needs to be baked with the required connector jars before deployment. We will build a custom Kafka connect docker image by using the below Dockerfile, 1 2 3 4 5 6 7 8 9 10 FROM confluentinc/cp-kafka-connect:7.3.1 RUN wget http://client.hub.confluent.io/confluent-hub-client-latest.tar.gz && tar -xzf confluent-hub-client-latest.tar.gz RUN chmod +x ./bin/confluent-hub ENV CONNECT_PLUGIN_PATH: "/usr/share/java,/usr/share/confluent-hub-components" RUN ./bin/confluent-hub install --no-prompt confluentinc/kafka-connect-datagen:0.6.0 RUN ./bin/confluent-hub install --no-prompt confluentinc/kafka-connect-jdbc:10.7.0 Following is the docker compose file for deploying Kafka Connect, KSQLDB server, KSQLDB CLI and Postgres DB docker-compose.yml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 version: '3.7' services: connect: build: . hostname: connect container_name: sample-connect ports: - "8083:8083" environment: CONNECT_BOOTSTRAP_SERVERS: "${KAFKA_BOOTSTRAP_SERVER}" CONNECT_SECURITY_PROTOCOL: SASL_SSL CONNECT_SASL_MECHANISM: PLAIN CONNECT_SASL_JAAS_CONFIG: | org.apache.kafka.common.security.plain.PlainLoginModule required \ username="${KAFKA_API_KEY}" \ password="${KAFKA_API_SECRET}"; CONNECT_REST_ADVERTISED_HOST_NAME: connect CONNECT_REST_PORT: 8083 CONNECT_GROUP_ID: test-connect-group CONNECT_CONFIG_STORAGE_TOPIC: docker-connect-configs CONNECT_CONFIG_STORAGE_REPLICATION_FACTOR: 3 CONNECT_OFFSET_FLUSH_INTERVAL_MS: 10000 CONNECT_OFFSET_STORAGE_TOPIC: docker-connect-offsets CONNECT_OFFSET_STORAGE_REPLICATION_FACTOR: 3 CONNECT_STATUS_STORAGE_TOPIC: docker-connect-status CONNECT_STATUS_STORAGE_REPLICATION_FACTOR: 3 CONNECT_PLUGIN_PATH: "/usr/share/java,/usr/share/confluent-hub-components" CONNECT_TOPIC_CREATION_ENABLE: "true" CONNECT_LOG4J_ROOT_LOGLEVEL: "INFO" CONNECT_INTERNAL_KEY_CONVERTER: "org.apache.kafka.connect.json.JsonConverter" CONNECT_INTERNAL_VALUE_CONVERTER: "org.apache.kafka.connect.json.JsonConverter" CONNECT_KEY_CONVERTER: "io.confluent.connect.avro.AvroConverter" CONNECT_KEY_CONVERTER_SCHEMAS_ENABLE: "true" CONNECT_KEY_CONVERTER_SCHEMA_REGISTRY_URL: "${SCHEMA_REGISTRY_URL}" CONNECT_KEY_CONVERTER_BASIC_AUTH_CREDENTIALS_SOURCE: USER_INFO CONNECT_KEY_CONVERTER_SCHEMA_REGISTRY_BASIC_AUTH_USER_INFO: "${SCHEMA_REGISTRY_API_KEY}:${SCHEMA_REGISTRY_API_SECRET}" CONNECT_VALUE_CONVERTER: "io.confluent.connect.avro.AvroConverter" CONNECT_VALUE_CONVERTER_SCHEMAS_ENABLE: "true" CONNECT_VALUE_CONVERTER_SCHEMA_REGISTRY_URL: "${SCHEMA_REGISTRY_URL}" CONNECT_VALUE_CONVERTER_BASIC_AUTH_CREDENTIALS_SOURCE: USER_INFO CONNECT_VALUE_CONVERTER_SCHEMA_REGISTRY_BASIC_AUTH_USER_INFO: "${SCHEMA_REGISTRY_API_KEY}:${SCHEMA_REGISTRY_API_SECRET}" CONNECT_CONNECTOR_CLIENT_CONFIG_OVERRIDE_POLICY: "All" CONNECT_CONUSMER_SECURITY_PROTOCOL: SASL_SSL CONNECT_CONUSMER_SASL_MECHANISM: PLAIN CONNECT_CONUSMER_SASL_JAAS_CONFIG: | org.apache.kafka.common.security.plain.PlainLoginModule required \ username="${KAFKA_API_KEY}" \ password="${KAFKA_API_SECRET}"; CONNECT_PRODUCER_SECURITY_PROTOCOL: SASL_SSL CONNECT_PRODUCER_SASL_MECHANISM: PLAIN CONNECT_PRODUCER_SASL_JAAS_CONFIG: | org.apache.kafka.common.security.plain.PlainLoginModule required \ username="${KAFKA_API_KEY}" \ password="${KAFKA_API_SECRET}"; ksqldb-server: image: confluentinc/cp-ksqldb-server:7.3.1 hostname: ksqldb-server container_name: ksqldb-server-container depends_on: - connect ports: - "8088:8088" # volumes: # - ./ksql.sql:/opt/ksql/ksql.sql environment: KSQL_CONFIG_DIR: "/etc/ksql" KSQL_AUTO_OFFSET_RESET: "earliest" KSQL_BOOTSTRAP_SERVERS: "${KAFKA_BOOTSTRAP_SERVER}" KSQL_HOST_NAME: ksqldb-server KSQL_LISTENERS: "http://0.0.0.0:8088" KSQL_CACHE_MAX_BYTES_BUFFERING: 0 KSQL_KSQL_SCHEMA_REGISTRY_URL: "${SCHEMA_REGISTRY_URL}" KSQL_KSQL_SCHEMA_REGISTRY_BASIC_AUTH_CREDENTIALS_SOURCE: USER_INFO KSQL_KSQL_SCHEMA_REGISTRY_BASIC_AUTH_USER_INFO: "${SCHEMA_REGISTRY_API_KEY}:${SCHEMA_REGISTRY_API_SECRET}" KSQL_KSQL_CONNECT_URL: "http://connect:8083" KSQL_KSQL_LOGGING_PROCESSING_TOPIC_REPLICATION_FACTOR: 3 KSQL_KSQL_LOGGING_PROCESSING_TOPIC_AUTO_CREATE: 'true' KSQL_KSQL_LOGGING_PROCESSING_STREAM_AUTO_CREATE: 'true' KSQL_LOG4J_ROOT_LOGLEVEL: INFO KSQL_KSQL_SERVICE_ID: "test-ksql-cluster" KSQL_KSQL_STREAMS_REPLICATION_FACTOR: 3 KSQL_KSQL_INTERNAL_TOPIC_REPLICAS: 3 KSQL_SECURITY_PROTOCOL: SASL_SSL KSQL_SASL_MECHANISM: PLAIN KSQL_SASL_JAAS_CONFIG: | org.apache.kafka.common.security.plain.PlainLoginModule required \ username="${KAFKA_API_KEY}" \ password="${KAFKA_API_SECRET}"; ksqldb-cli: image: confluentinc/cp-ksqldb-cli:7.3.1 container_name: ksqldb-cli entrypoint: /bin/sh tty: true pg-database: image: "postgres:11" ports: - "5432:5432" environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: password POSTGRES_DB: postgres The Kafka Connect and KSQLDB services will connect to Kafka cluster in Confluent Cloud using the bootstrap server and the SASL credentials provided as environment variables for the respective services. The Schema registry URL and its credentials are also provided for both the services. The config CONNECT_TOPIC_CREATION_ENABLE: "true" needs to be set up in Kafka Connect cluster to enable the input topic creation through Source connectors. Start the docker services in build mode to build the custom Kafka Connect image using the Dockerfile we created, 1 docker-compose up -d --build Once all the services are successfully up, attach to the KSQLDB CLI container’s bash, 1 docker exec -it ksqldb-cli bash Connect to the KSQLDB server inside the KSQLDB CLI container, 1 ksql http://ksqldb-server:8088 Deploy the Datagen Source connector, 1 2 3 4 5 6 7 8 9 10 11 CREATE SOURCE CONNECTOR "ClickstreamDataGenSourceConnector" WITH ( "connector.class"='io.confluent.kafka.connect.datagen.DatagenConnector', "kafka.api.key"='${KAFKA_API_KEY}', "kafka.api.secret"='${KAFKA_API_SECRET}', "kafka.topic"='clickstream_cloud_input', "output.data.format"='AVRO', "quickstart"='SHOE_CLICKSTREAM', "topic.creation.default.partitions"='1', "topic.creation.default.replication.factor"='3', "tasks.max"='1' ); Create the Kafka stream from the input topic clickstream_cloud_input, 1 2 3 4 5 CREATE OR REPLACE STREAM CLICKSTREAM_CLOUD_STREAM (PRODUCT_ID VARCHAR, USER_ID VARCHAR, VIEW_TIME INT, PAGE_URL VARCHAR, IP VARCHAR, TS BIGINT) WITH (kafka_topic='clickstream_cloud_input', partitions=1, value_format='AVRO', timestamp='TS'); Create the aggregated table backed by a output topic clickstream_cloud_output, 1 2 3 4 5 6 7 8 CREATE OR REPLACE TABLE USER_PRODUCT_VIEWTIME WITH (kafka_topic='clickstream_cloud_output', partitions=1, key_format='AVRO', value_format='AVRO') AS SELECT USER_ID, PRODUCT_ID, AS_VALUE(USER_ID) AS USERID, AS_VALUE(PRODUCT_ID) AS PRODUCTID, SUM(VIEW_TIME) AS TOTAL_VIEW_TIME, WINDOWEND AS END_TIME, WINDOWSTART AS START_TIME FROM CLICKSTREAM_CLOUD_STREAM WINDOW TUMBLING (SIZE 1 MINUTES, RETENTION 7 DAYS) GROUP BY USER_ID, PRODUCT_ID; Create the JDBC Postgres Sink Connector to sink data to the local Postgres database, 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 CREATE SINK CONNECTOR "PostgresClickstreamSinkConnector" WITH ( 'connector.class' = 'io.confluent.connect.jdbc.JdbcSinkConnector', 'connection.url' = 'jdbc:postgresql://pg-database:5432/postgres?user=postgres&password=password&ssl=false', 'topics' = 'clickstream_cloud_output', 'input.data.format' = 'AVRO', 'input.key.format' = 'AVRO', 'delete.enabled' = 'false', 'ssl.mode' = 'prefer', 'insert.mode' = 'UPSERT', 'table.name.format' = 'clickstream_user_product_viewtime', 'db.timezone' = 'UTC', 'pk.mode' = 'record_value', 'pk.fields' = 'USERID,PRODUCTID', 'auto.create' = 'true', 'auto.evolve' = 'true', 'quote.sql.identifiers' = 'ALWAYS', 'batch.sizes' = '3000', 'tasks.max' = '1', 'consumer.override.sasl.mechanism' = 'PLAIN', 'consumer.override.security.protocol'= 'SASL_SSL', 'consumer.override.sasl.jaas.config' = 'org.apache.kafka.common.security.plain.PlainLoginModule required username=\"${KAFKA_API_KEY}\" password=\"${KAFKA_API_SECRET}\";' Conclusion In conclusion, building an end-to-end streaming pipeline using Kafka Connect and KSQLDB can be a powerful way to enable real-time data processing and analytics. By leveraging Kafka Connect for data ingestion and KSQLDB for data processing and analysis, developers can build complex streaming applications that can scale horizontally as needed. Deploying this architecture in a managed environment such as Confluent Cloud provides several benefits, including reduced infrastructure management overhead, automatic scaling, and built-in support for high availability and disaster recovery. However, this comes at the cost of higher pricing and potentially reduced flexibility in terms of configuration and customization. On the other hand, self-hosted deployment mode provides greater control and flexibility over the deployment and configuration of Kafka Connect and KSQLDB. However, this approach requires more infrastructure management and may require more upfront investment in terms of hardware and software resources. --- # The Kafka benchmarking suite URL: https://platformatory.io/blog/kafka-client-performance-metrics/ Published: 2023-03-30 Authors: Lakshminarasimhan Parthasarathy, Pavan Keshavamurthy Categories: Kafka, Performance, Observability, Kubernetes There are numerous parameters we have to consider tweaking when benchmarking a Kafka cluster. Irrespective of these parameters, we optimize along the following dimensions: Throughput: The volume of data moved across the cluster in a given unit of time. Durability: Are we minimizing the chance of messages getting lost Availability: How quickly can my Kafka cluster recover from a failure scenario and be operational again? Latency: How soon can a message be consumed after it is produced? Defining our problem statement The purpose of a Kafka benchmarking exercise is to initially establish baseline performance characteristics, mainly for throughput and end to end latency. We then iteratively optimize these quantities by modifying various producer and consumer parameters, running the benchmark again, measuring the quantities. These steps are done in a “rinse and repeat” fashion till we hit our desired performance metrics. There are quite a few performance testing frameworks in the open which aid in doing this. We prepare a wishlist of items required for a good benchmarking system, like: It should be close to a realistic production scenario. No toy benchmarking. Ability to snapshot and visualize the data from various test runs. Ease of setup. The benchmarking system itself shouldn’t be complicated to setup with a lot of configuration landmines. Nothing is more dangerous than a misconfigured benchmarking system which gives us false promises. Let’s see how existing setups measure up against this wishlist. Openmessaging benchmarks The Openmessaging benchmark framework is a vendor-neutral suite of tools which eases benchmarking of distributed benchmarking systems. In addition to Kafka, this framework provides benchmarking tools for other messaging systems like RabbitMQ and Apache Pulsar. In essence, Openmessaging benchmarking involves the following steps broadly: Spin up the infrastructure needed to run Kafka in the cloud using Terraform Provision and install Kafka clusters and clients using Ansible playbook Run benchmarks from client hosts. NOTE that this can be run in a distributed manner as well across multiple hosts. One of the biggest selling points of Openmessaging benchmarks is that they are as close to realistic scenarios as possible. In fact, this is one of the stated goals of the project. There is also the provision to download the metrics data for each test run/scenario. We observed a few shortcomings with Openmessaging benchmarks. The inability to measure end to end latency. This is a key metric in many scenarios and there is no documented way to measure this in Openmessaging suite. Ease of setup. Openmessaging provides all the necessary scaffold scripts like Terraform and Ansible to run the test. This could be made easier. There is an option to deploy it as a Helm chart, which closely resembles our approach as well. But this isn’t documented. As a sub-idea of 2, we don’t have an easy way to visualize these numbers. We all love to see the big picture instead of staring at a spreadsheet full of numbers. It would be great if we can pipe the output straight to tools like Grafana. Apache Trogdor Apache Trogdor is a test framework for Kafka. Although it does excellent performance testing, Trogdor emphasizes a lot of fault testing. The idea is to run a Trogdor agent in every cluster node and a Trogdor coordinator daemon which manages the agents and tasks in the cluster. The agent can simulate a fault by crashing one of the brokers. We measure the message durability, adjust the parameters and re-run the process again. Confluent cloud uses Trogdor to performance test its infrastructure. Again, we found the following things lacking in Trogdor. No way to measure end to end latency. The RoundTripWorkload is a close match for what we were looking for, but doesn’t quite cut it. It doesn’t emit metrics which can be visualized. There is a provision to show the status of a submitted task. This gives a snapshot of the task(a task is a specific, defined benchmark scenario), like time taken, number of messages sent, 99th percentile latency etc. We have to run the agent and coordinator daemon processes in the cluster. Sometimes, due to various limitations, we might not be able to do so. Jmeter Jmeter is an excellent tool to benchmark Kafka clusters and scores pretty high on the “ease of setup” factor. PepperBox, a specialized Kafka load generator for Jmeter, is a prerequisite for running load tests using Jmeter. However, Jmeter suffers from the following limitations: We have to write the consumer client code for running the end to end tests. There is no way to measure the latency. We had to tweak the consumer to write the timestamp to a file. Ideally, there should be a complementing tool for PepperBox at the consumer end for this. Kafka perf tools Kafka offers a set of performance testing tools for the producer, consumer and also to measure end to end latency. This is the least common denominator of all the tools out there which fits our bill, but we’re not quite out there yet. We don’t have the option to load test a production replica scenario(Ex. Parallel producers/consumers). There’s also the “ease of setup” factor missing. We have to clean up the resources and re-run the process for a new scenario. Finally, there is no way to record and view the metrics. We will build a Prometheus based scaffold to send these metrics. In the rest of the post, we shall focus on how we’ve fixed these issues and created a robust and reliable performance testing framework which fulfills our wishlist. Prerequisites You should have a Kafka cluster which needs to be benchmarked(Duh!). Arguably the fastest way to get your hands on a fairly production ready Kafka cluster is to sign up for a Confluent cloud account and spin up a new cluster. Benchmarking using kafka provided tools For those of you who are new to benchmarking using Kafka perf-tools, here’s a brief recap. First, you create a new topic where you want to send your records. 1 2 3 4 5 6 7 8 $ kafka-topics \ # <-------- (1) --if-not-exists \ --topic mytopic \ # <-------- (2) --create \ --bootstrap-server xxx-yyyy.us-west4.gcp.confluent.cloud:9092 \ # <-------- (3) --replication-factor 3 \ # <-------- (4) --partitions 1 \ # <-------- (5) --command-config kafka.properties # <-------- (6) kafka-topics is the CLI tool which ships with Apache Kafka(as kafka-topics.sh) and confluent platform package. Name of the topic you want to create The bootstrap server URL. You get this from your confluent cloud account. Replication factor for your topic. Please update it with your desired replication factor. The number of partitions for the topic. Again, update it to suit your needs The kafka.properties file, needed for all the CLI tools we will run. Let’s quickly take a look at the contents of kafka.properties. 1 2 3 4 bootstrap.servers=xxx-yyyy.us-west4.gcp.confluent.cloud:9092 # <-- (1) security.protocol=SASL_SSL # <-- (2) sasl.jaas.config=org.apache.kafka.common.security.plain.PlainLoginModule required username='BADRI123SZK5QZJI' password='Supersecretlongpasswordgivenbyconfluentcloud'; # <-- (3) sasl.mechanism=PLAIN # <-- (4) The bootstrap server URL, which you can obtain from confluent cloud. Confluent cloud uses SASL_SSL for authentication. The user name and password can be obtained from confluent cloud. NOTE that this properties file will be used across the board for the producer and consumer benchmark tools as well. Time to pump in some messages to this topic. 1 2 3 4 5 6 7 8 $ kafka-producer-perf-test \ # <-- (1) --topic mytopic \ # <-- (2) --num-records 10000 \ # <-- (3) --record-size 1024 \ # <-- (4) --throughput -1 \ # <-- (5) --producer-props acks=all client.id=producer-01 \ # <-- (6) --producer.config kafka.properties --print-metrics # < -- (7) We run the kafka-producer-perf-test CLI tool for this. We send messages to the topic we created just now. We’re sending 10k records. The size of each of these records is 1024 bytes. We don’t want to throttle the number of messages per second. Hence, we set it to -1. Number of acknowledgements the leader broker must have received before acknowledging to the producer. We also specify the client ID here. Print the producer metrics. We should get an output which looks similar to this. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 1 records sent, 0.2 records/sec (0.00 MB/sec), 5289.0 ms avg latency, 5289.0 ms max latency. 1215 records sent, 240.6 records/sec (0.24 MB/sec), 4727.5 ms avg latency, 7196.0 ms max latency. 1275 records sent, 246.3 records/sec (0.24 MB/sec), 9746.1 ms avg latency, 12365.0 ms max latency. 1500 records sent, 269.5 records/sec (0.26 MB/sec), 14727.0 ms avg latency, 17925.0 ms max latency. 1425 records sent, 283.6 records/sec (0.28 MB/sec), 20428.6 ms avg latency, 22947.0 ms max latency. 1650 records sent, 320.0 records/sec (0.31 MB/sec), 25312.8 ms avg latency, 28097.0 ms max latency. 1200 records sent, 238.0 records/sec (0.23 MB/sec), 30665.2 ms avg latency, 33137.0 ms max latency. 1200 records sent, 212.7 records/sec (0.21 MB/sec), 35153.8 ms avg latency, 38780.0 ms max latency. 10000 records sent, 223.613596 records/sec (0.22 MB/sec), 21165.35 ms avg latency, 41544.00 ms max latency, 21647 ms 50th, 38785 ms 95th, 40823 ms 99th, 41544 ms 99.9th. Metric Name Value app-info:commit-id:{client-id=producer-1} : 06652ad189d0cbf0 app-info:start-time-ms:{client-id=producer-1} : 1653549654259 app-info:version:{client-id=producer-1} : 6.2.1-ce kafka-metrics-count:count:{client-id=producer-1} : 113.000 producer-metrics:batch-size-avg:{client-id=producer-1} : 15548.256 producer-metrics:batch-size-max:{client-id=producer-1} : 15556.000 producer-metrics:batch-split-rate:{client-id=producer-1} : 0.000 producer-metrics:batch-split-total:{client-id=producer-1} : 0.000 producer-metrics:buffer-available-bytes:{client-id=producer-1} : 33554432.000 ... producer-topic-metrics:record-error-total:{client-id=producer-1, topic=mytopic} : 0.000 producer-topic-metrics:record-retry-rate:{client-id=producer-1, topic=mytopic} : 0.000 producer-topic-metrics:record-retry-total:{client-id=producer-1, topic=mytopic} : 0.000 producer-topic-metrics:record-send-rate:{client-id=producer-1, topic=mytopic} : 250.752 producer-topic-metrics:record-send-total:{client-id=producer-1, topic=mytopic} : 10000.000 Let’s consume the messages we created. 1 2 3 4 5 6 7 $ kafka-consumer-perf-test \ --topic mytopic \ # <-- (1) --bootstrap-server xxx-yyyy.us-west4.gcp.confluent.cloud:9092 \ # <-- (2) --messages 1000 \ # <-- (3) --consumer.config kafka.properties # <-- (4) --print-metrics \ --timeout=100000 # <-- (5) We use the same topic. We have to specify the bootstrap server. The number of messages we want to consume. We refer to the same kafka.properties file. The amount of time the consumer process waits before the broker returns records. Here’s a sample output from a consumer perf test run. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 start.time, end.time, data.consumed.in.MB, MB.sec, data.consumed.in.nMsg, nMsg.sec, rebalance.time.ms, fetch.time.ms, fetch.MB.sec, fetch.nMsg.sec 2023-03-30 13:18:56:066, 2023-03-30 13:19:11:826, 0.9766, 0.0620, 1000, 63.4518, 6219, 9541, 0.1024, 104.8108 Metric Name Value consumer-coordinator-metrics:assigned-partitions:{client-id=consumer-perf-consumer-24667-1} : 0.000 consumer-coordinator-metrics:commit-latency-avg:{client-id=consumer-perf-consumer-24667-1} : 218.500 consumer-coordinator-metrics:commit-latency-max:{client-id=consumer-perf-consumer-24667-1} : 222.000 consumer-coordinator-metrics:commit-rate:{client-id=consumer-perf-consumer-24667-1} : 0.057 consumer-coordinator-metrics:commit-total:{client-id=consumer-perf-consumer-24667-1} : 2.000 consumer-coordinator-metrics:failed-rebalance-rate-per-hour:{client-id=consumer-perf-consumer-24667-1} : 88.703 consumer-coordinator-metrics:failed-rebalance-total:{client-id=consumer-perf-consumer-24667-1} : 1.000 consumer-coordinator-metrics:heartbeat-rate:{client-id=consumer-perf-consumer-24667-1} : 0.081 ... consumer-fetch-manager-metrics:records-lag-max:{client-id=consumer-perf-consumer-24667-1} : 41500.000 consumer-fetch-manager-metrics:records-lag:{client-id=consumer-perf-consumer-24667-1, topic=mytopic, partition=0} : 41000.000 consumer-fetch-manager-metrics:records-lead-avg:{client-id=consumer-perf-consumer-24667-1, topic=mytopic, partition=0} : 750.000 consumer-fetch-manager-metrics:records-lead-min:{client-id=consumer-perf-consumer-24667-1, topic=mytopic, partition=0} : 500.000 consumer-fetch-manager-metrics:records-lead-min:{client-id=consumer-perf-consumer-24667-1} : 500.000 consumer-fetch-manager-metrics:records-lead:{client-id=consumer-perf-consumer-24667-1, topic=mytopic, partition=0} : 1000.000 consumer-fetch-manager-metrics:records-per-request-avg:{client-id=consumer-perf-consumer-24667-1, topic=mytopic} : 1000.000 consumer-fetch-manager-metrics:records-per-request-avg:{client-id=consumer-perf-consumer-24667-1} : 1000.000 kafka-metrics-count:count:{client-id=consumer-perf-consumer-24667-1} : 61.000 The typical way to run Kafka benchmarks is to take a set of parameters for the producer and consumer, do a set of sample runs with those parameters, and record the metrics we get. We repeat this loop until we get the desired numbers. This can be likened to an OODA (Observe Orient Decide Act) loop, where the mapping looks like this: Observe - Look at the printed metrics for each run. Orient - Find out what configuration tweak led to this set of outcomes. Decide - Figure what configuration parameters to change for next run. Act - Run the benchmarks CLI program. Applying the OODA loop to the plain vanilla kafka benchmark CLI tools can get messy quickly. For instance, what should I be doing to run 20 parallel producers? Also, how can I move all these metrics to a central location for later analysis/charting? What numbers did we get the last time we ran for a particular set of config values? We fix these open questions in the rest of the post. Take 2 - Kubernetes One major change in our benchmarking procedure will be the fact that we will move all our benchmark CLI tools to Kubernetes services. So, the prerequisite here would be for you to have a working Kubernetes cluster with the kubectl client. Let’s try running this as a Kubernetes Job. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 apiVersion: batch/v1 kind: Job metadata: name: producer # <-------- (1) labels: type: producer spec: completions: 3 # <-------- (2) parallelism: 3 template: spec: initContainers: # <-------- (3) - name: topics image: confluentinc/cp-kafka:7.3.2 # <-------- (4) command: - /bin/sh - -c - | kafka-topics \ --if-not-exists \ --topic mytopic \ --create \ --bootstrap-server xxx-yyyy.us-west4.gcp.confluent.cloud:9092 \ --replication-factor 3 \ --partitions 1 \ --command-config /mnt/kafka.properties volumeMounts: - name: kafka-properties # <-------- (5) mountPath: /mnt containers: - name: producer image: confluentinc/cp-kafka:7.3.2 command: - /bin/sh - -c - | kafka-producer-perf-test \ # <-------- (6) --topic perf-test \ --num-records 10000 \ --record-size 1024 \ --throughput -1 \ --producer-props acks=1 client.id=foo batch.size=1000 linger.ms=100 compression.type=lz4 \ --producer.config /mnt/kafka.properties volumeMounts: - name: kafka-properties mountPath: /mnt volumes: - name: kafka-properties secret: secretName: "kafka-client-config" restartPolicy: Never backoffLimit: 4 We run a job called “producer”. Indicates the number of parallel producer jobs we want to run. We run an initcontainer which creates the topic if it doesn’t exist. The latest confluent kafka container image at the time of writing this. Please substitute with a more recent image if applicable. We model the kafka.properties as a kubernetes secret and mount it here as a volume. We run the actual producer perf test process with all the parameters. Now, we can run this in a Kubernetes cluster and get the same OODA loop running. But what changed, other than moving everything inside containers? For starters, we can parallelize the process simply by increasing the parallelism spec of the job. Also, we can ship these metrics to Prometheus if we bake the kafka container image with a JMX agent. 1 2 3 4 5 6 7 8 9 10 11 12 FROM confluentinc/cp-kafka:7.3.2 # <---------- (1) COPY jmx /usr/app # <---------- (2) # Install Prometheus RUN curl -s https://api.github.com/repos/prometheus/prometheus/releases/latest \ | grep browser_download_url \ | grep linux-amd64 \ | cut -d '"' -f 4 \ | wget -qi - && \ tar xf prometheus*.tar.gz && \ cd prometheus*/ && \ mv prometheus .. # <---------- (3) We start with the official Confluent Kafka base image. We copy over the JMX agent jar and corresponding YAML configuration file tailored for Kafka. We install Prometheus binary. Prometheus is typically configured for pull based metrics. In our case, we run the prometheus binary in a push-based fashion. We have a JMX server running in port 7071 for the duration of the Job. We configure Prometheus to run in agent mode, where it will fetch metrics from the JMX server and push to a pre-configured write endpoint in the Prometheus server. 1 ./prometheus --enable-feature=agent --config.file="/prom/prometheus.yml" --log.level=error Let’s take a quick look at the prometheus agent configuration. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 # my global config global: scrape_interval: 15s # Set the scrape interval to every 15 seconds. Default is every 1 minute. evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute. # scrape_timeout is set to the global default (10s). # A scrape configuration containing exactly one endpoint to scrape: # Here it's Prometheus itself. scrape_configs: # The job name is added as a label `job=` to any timeseries scraped from this config. - job_name: "jmx" # <---- (1) # metrics_path defaults to '/metrics' # scheme defaults to 'http'. static_configs: - targets: ["localhost:7071"] # <---- (2) labels: env: "dev" # <---- (3) relabel_configs: - source_labels: [__address__] target_label: hostname regex: "([^:]+)(:[0-9]+)?" replacement: "${1}" remote_write: - url: "http://your-prometheus-url/api/v1/write" # <---- (4) Name of the prometheus Job. The target from which we scrape the metrics. A unique identifier for every run. The Prometheus server url to write the metrics to. NOTE that the Prometheus server should have “remote write receiver” enabled for the prometheus agent to send JMX metrics. I’d argue that we didn’t gain much from this transition, except for the Prometheus integration. I still have to change the config parameters for the next run, kubectl apply it, and track the metrics. We can do better. We could run a Helm chart with a parameterized set of input values and ship off these metrics to Prometheus. Before we go into the details of the Helm chart, let’s define how a typical testing loop looks like. Come up with a baseline test on standard hardware / test conditions Identify specific scenarios (these translate into producer and consumer configs) Configure accordingly and run the test Look at the client “blackbox” profile for throughput, latency Look at the client “whitebox” profile - extended JMX metrics Look at the server-side “blackbox” profile - throughput, latency Look at the server-side “whitebox” profile - extended JMX metrics Look at the log levels both client and server side - if needed, increase it to look at specific problems, if any Repeat-rinse steps 3 - 8 and infer performance based on deviation from the baseline. Take 3 - Helm chart We take the following artifacts, The kafka.config secret Producer perf test job Consumer perf test job Prometheus config And templatize them, package them as a Helm chart. We model every iteration in our OODA loop as a new helm release with its own set of helm values. The Helm chart does the following: Run a distributed set of producer jobs(defined by the producer.count parameter) run a distributed consumer - simplest is to have an array of consumers (and topics) defined so we don’t get into managing concurrency; instead, we just create consumer.count number of consumer Jobs to paralelly consume from the topic. Note that we will need the consumer to run with a countdown latch or timeout. Here’s a performance test release with values optimized for throughput. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 topic: name: "t1_benchmark" replicationFactor: 3 partitions: 1 broker: url: "xxx-yyyy.us-west4.gcp.confluent.cloud:9092" username: "XXXXX" password: "YXYXYXYXY2341234wesfdf345234" producer: enabled: true image: "confluentinc/cp-kafka:7.3.2" recordsCount: 1000 recordSizeBytes: 1024 throughput: "-1" acks: 1 count: 3 params: "batch.size=100000 linger.ms=100 compression.type=lz4" consumer: enabled: true image: "confluentinc/cp-kafka:7.3.2" messagesCount: 1000 count: 1 timeout: 100000 And here’s another set of values optimized for high durability. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 topic: name: "t1_benchmark" replicationFactor: 3 partitions: 1 broker: url: "xxx-yyyy.us-west4.gcp.confluent.cloud:9092" username: "XXXXX" password: "YXYXYXYXY2341234wesfdf345234" producer: enabled: true image: "confluentinc/cp-kafka:7.3.2" recordsCount: 1000 recordSizeBytes: 1024 throughput: "-1" acks: "all" count: 3 params: "enable.idempotence=true max.in.flight.requests.per.connection=1" consumer: enabled: true image: "confluentinc/cp-kafka:7.3.2" messagesCount: 1000 count: 1 timeout: 100000 A quick aside on Prometheus and Grafana The code accompanying this post ships with a custom Helm chart which piggy backs on the Kube Prometheus stack to install Prometheus, Grafana and a couple of associated producer and consumer dashboards. This chart will also wire Prometheus as a datasource for the Grafana installation. You can install this setup using the following command. 1 helm upgrade --install prom-stack ./kube-prometheus-kafka-chart The Prometheus console can be viewed in the browser by issuing a port-forward command. 1 kubectl port-forward svc/prometheus-operated 9090:9090 We can do something similar for the Grafana web console as well. 1 kubectl port-forward svc/prom-stack-grafana 8080:80 Grafana requires credentials, which are admin and platformatory(the default password in the Helm chart). Running the performance tests Once we have the scaffold ready, we run a helm release using the following command, 1 helm upgrade --install march-25-2023-durability-producer ./kafka-performance-metrics-chart --values durability-producer-values.yml This is how a typical producer dashboard would look like. Next, we run the corresponding consumer job using the Helm chart. 1 helm upgrade --install march-25-2023-durability-consumer ./kafka-performance-metrics-chart --values durability-consumer-values.yml …and process the consumer dashboard. Shipping metrics to other systems The performance metrics Helm chart has provision to write openmetrics to any system which supports the Prometheus remote write feature. This configuration can be changed in the values.yaml as illustrated below: 1 2 3 prometheus: remote_write: - url: "http://prom-stack-kube-prometheus-prometheus:9090/api/v1/write" As a quick example, if you want to use New Relic to process the metrics, your configuration would look like this: 1 2 3 4 prometheus: remote_write: - url: https://metric-api.newrelic.com/prometheus/v1/write?prometheus_server=kafka-perf-test bearer_token: xxxxxxxxxxxxxxxxxxxxxxxxxxx The Helm charts and the associated code mentioned in this post can be found here. --- # Command Processing and Event Driven Workflows with Apache Kafka and Airflow URL: https://platformatory.io/blog/Command_Processing_and_Event_Driven_Workflows_with_Apache_Kafka_and_Airflow/ Published: 2023-03-30 Authors: Ashwin Venkatesan Categories: Event-Driven Architecture, Kafka, Workflow Orchestration Introduction In today’s world, data processing has become an essential part of businesses. With the rise of big data, companies are looking for efficient ways to process data quickly and accurately. Apache Kafka and Apache Airflow are two popular technologies used for this purpose. Apache Kafka is a distributed messaging system designed to handle large amounts of data efficiently. It can be used as a real-time stream processing platform, and it is widely used for its ability to handle high throughput and low latency. Kafka is a popular choice for building event-driven architectures because of its persistence and scalability. Apache Airflow, on the other hand, is an open-source platform used for managing and scheduling complex data pipelines. Airflow allows users to define and execute workflows, making it easier to manage and monitor data pipelines. Airflow boasts a wide range of operators for various types of operations and integration with third party applications. Command Processing and Event Driven Workflows Command processing refers to a software design pattern in which an application receives and executes commands from users or other systems. In general, the application receives a command and then executes it in a synchronous manner, meaning that it waits for the command to complete before executing the next one. Command processing is simpler to implement and provides greater control over the order in which tasks are executed, making it well-suited for applications where the user is in direct control of the system. On the other hand, event-driven workflows are based on the idea of reacting to events that occur within a system, rather than waiting for a command to be executed. This pattern is often used in complex systems, such as distributed systems, to ensure that actions are taken in response to specific events, without the need for manual intervention. Event-driven workflows are more flexible and can adapt to changing conditions in real-time, making them ideal for systems that require a high degree of automation or respond to external events. But in reality, in most cases,the commands need to processed in real-time to quickly inform the dependent systems to effect the appropriate action derived from the command. By combining command processing with the event driven architecture, we can process commands asynchronously in real-time and trigger actions derived from the command. Let’s see how to achieve this with the help of Apache Kafka and Apache Airflow. Command Processing in Apache Kafka Kafka is designed to handle high volumes of data in real-time, making it well-suited for use in complex systems where events are monitored continuously. Some of the capabilities of Kafka which makes it ideal for command processing, Persistent: Kafka is designed to be highly persistent, ensuring that messages are not lost even if there are failures or crashes in the system. Low latency: Kafka is optimized for low latency, enabling it to deliver real-time data streams with minimal delay. System of record: Kafka can be a centralised system of record for all the events occurred. This also gives us the flexibility to reprocess events in the arrived order in case of failure or requirement. Fan Out/Parallelism: Many event-driven apps need fan out = “write once, read many”- that is, multiple applications may be interested in subscribing to and reacting to a single event Kafka topics can act as the medium for passing commands and events between different components of the system. In this architecture, commands are sent to a specific topic by a user or external system, and then consumed by a component responsible for processing that particular command. This architecture also allows for the separation of concerns between different components, making it easier to manage and maintain the system over time. For example, consider an e-commerce platform where customers can place orders for products. When a customer places an order, a command is sent to a specific Kafka topic, which is consumed by an order processing component. The component then executes the command by creating an order record in a database and generating an event indicating that a new order has been placed. This event is then sent to another Kafka topic, which is consumed by a shipping component responsible for initiating the shipping process. Orchestrating Event Workflows in Apache Airflow Many applications process events in step-wise workflows (also known as Staged Event Driven Architecture) – these workflows need control on the individual steps (including sequencing, dependencies on previous steps, handling failures, parallel processing etc). Airflow to this end is the best orchestration platform for performing these with a purely Python interface (something that developers love). Airflow allows users to define workflows as Directed Acyclic Graphs (DAGs), where nodes represent individual tasks and edges represent dependencies between those tasks. Airflow provides a number of key features to support workflow management, including: Scheduling and automation: Airflow allows users to define schedules and automate workflow execution, ensuring that tasks are executed in the correct order and at the right time. It also supports passing on variables from upstream tasks to downstream tasks making dynamic conditional execution possible. Monitoring and logging: Airflow provides rich monitoring and logging capabilities, allowing users to track the progress of workflows, diagnose issues, and optimize performance. Extensibility: Airflow supports custom operators, sensors, and hooks, allowing users to interact with a wide range of systems and technologies. Alerting: Airflow provides built-in alerting capabilities, allowing you to track the progress of your pipeline and receive notifications if anything goes wrong. Compatibility: Airflow supports a wide range of data processing tools and frameworks, including Apache Kafka, Apache Spark, and TensorFlow, making it a highly compatible choice for event processing use cases. So, Apache Airflow is not just a great tool for both classic data integration & ETL/ELT oriented processing needs (in the analytics plane) but also orchestration of event driven workflows (in the operational plane). Architecture A general architecture is as follows, Initially, the command stream is produced to a Kafka topic from the user or external systems. A command dispatcher service (like a Kafka consumer) handles reading & committing offsets including hand off to Airflow by invoking the concerned DAG (via it’s REST interface). By doing this, we therefore separate consuming from processing. Airflow DAG itself is parametrized to process one command / event at a time. This therefore provides granular observability and auditable controls of what happened, thus enabling retrying/re-processing or dead-letter queue. This pattern could thus be used for: Analytical data processing closely tied to events (such as CDC) Handle patterns such as CQRS with projections (Airflow DAG computes projections) Just general event workflows with chained actions (when this happens, the following chain of other events must occur) We must note that this architecture while useful, may not suit high concurrency because of the nature of DAG processing for the following reasons, Each DAG run processes only one event at a time (as opposed to a batch) and thus has a large cost. There are also consequent impacts on the dispatcher’s ability to maintain strict order in the face of DAG run failures. Therefore, processing order cannot be guaranteed in high concurrency mode. This architecture is more suited for low-concurrency scenarios requiring granular execution level observability of command processes. Now, lets see an example of how to implement the above defined architecture. Prerequisites Kafka cluster running remotely or locally. We will be using a Confluent cloud cluster in this demo. You can easily set up a Confluent cloud cluster by signing up if you have not already. Python environment with following packages, 1 confluent-kafka[avro] Generate Command Stream For the purposes of this demo, we will send the events to a topic using a Kafka Producer python client. A topic called events_topic has already been created in advance. The client config file to connect to Kafka cluster will look like the following, kafka_server.config 1 2 3 4 5 6 7 8 9 bootstrap.servers=: security.protocol=SASL_SSL sasl.mechanisms=PLAIN sasl.username= sasl.password= # Required connection configs for Confluent Cloud Schema Registry schema.registry.url= basic.auth.credentials.source=USER_INFO basic.auth.user.info=: An example message for the event_topic is as follows, 1 2 3 4 { "command" : "app.send_email_alert", "params": "{\"email\": \"test@email.com\"}" } where, command - The command which needs to be executed. This will also help us determine the dag which needs to be called in case of multiple dags. params - A JSON string which contains all the required arguments for a DAG run. This can vary based on the type of event or command. Following is the sample producer code to produce events to the event_topic , 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 from confluent_kafka import Producer from confluent_kafka.serialization import StringSerializer from confluent_kafka.schema_registry import SchemaRegistryClient from confluent_kafka.schema_registry.avro import AvroSerializer from confluent_kafka.serialization import SerializationContext, MessageField import json import argparse def read_ccloud_config(config_file): conf = {} with open(config_file) as fh: for line in fh: line = line.strip() if len(line) != 0 and line[0] != "#": parameter, value = line.strip().split('=', 1) conf[parameter] = value.strip() return conf def pop_schema_registry_params_from_config(conf): """Remove potential Schema Registry related configurations from dictionary""" conf.pop('schema.registry.url', None) conf.pop('basic.auth.user.info', None) conf.pop('basic.auth.credentials.source', None) return conf if __name__ == '__main__': # Read arguments and configurations and initialize parser = argparse.ArgumentParser(description='Kafka Producer') parser.add_argument('--config_file', required=True,help='Absolute path to configurations file that contains properties used to configure a Kafka producer') parser.add_argument('--topic', required=False, help='Kafka topic to produce messages to.') config_file = args.config_file topic = args.topic conf = read_ccloud_config(config_file) schema_registry_conf = { 'url': conf['schema.registry.url'], 'basic.auth.user.info': conf['basic.auth.user.info']} schema_registry_client = SchemaRegistryClient(schema_registry_conf) event_schema = { "type" : "record", "name" : "EventSchema", "namespace" : "event", "fields" : [ { "name" : "command", "type" : "string", "doc" : "Command to process and the DAG to trigger" }, { "name" : "params", "type" : "string", "doc" : "Arguments for event workflow specific DAG" } ], "doc:" : "Schema of example command" } schema_str = json.dumps(event_schema) event_avro_serializer = AvroSerializer(schema_registry_client = schema_registry_client, schema_str = schema_str) string_serializer = StringSerializer('utf_8') producer_conf = pop_schema_registry_params_from_config(conf) producer = Producer(producer_conf) delivered_records = 0 # Optional per-message on_delivery handler (triggered by poll() or flush()) # when a message has been successfully delivered or # permanently failed delivery (after retries). def acked(err, msg): global delivered_records """Delivery report handler called on successful or failed delivery of message """ if err is not None: print("Failed to deliver message: {}".format(err)) else: delivered_records += 1 print("Produced record to topic {} partition [{}] @ offset {}" .format(msg.topic(), msg.partition(), msg.offset())) event_json = { "event" : "app.send_email_alert", "params": "{\"email\": \"test@email.com\"}" } producer.produce(topic=topic, key=string_serializer("event"), value=avro_serializer(event_json, SerializationContext(topic, MessageField.VALUE)), on_delivery=acked) print("\nFlushing records...") producer.flush() Run the above python code with topic and config file as arguments, 1 python producer.py --topic event_topic --config_file kafka_server.config Download and setup Airflow For this tutorial purposes, we will run airflow in docker. For Production, Airflow supports helm charts for Kubernetes deployment. We will be following this link to set up Airflow in docker. Open a terminal window and navigate to the working directory. 1 cd airflow_kafka Fetch the docker-compose.yml file, 1 curl -LfO 'https://airflow.apache.org/docs/apache-airflow/2.3.2/docker-compose.yaml' Create the required folders for docker compose and set the airflow uid (for Linux), 1 2 mkdir -p ./dags ./logs ./plugins echo -e "AIRFLOW_UID=$(id -u)" > .env Run database migrations and create the first user account, 1 docker-compose up airflow-init Now the Airflow is set up and can be started by executing, 1 docker-compose up -d Airflow web UI can be accessed at http://localhost:8080/ Define Event Workflow DAG Event-workflow dags should be defined in the Airflow dags folder for the airflow to recognize it. A dag can be a sequence of tasks to be executed to process an incoming event. In this example, a DAG to send email alerts on trigger will be used. This concept can be extended to any type of DAGs with different operators. /opt/airflow/dags/send_email.py 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 from datetime import datetime, timedelta from airflow import DAG from airflow.operators.email_operator import EmailOperator default_args = { 'owner': 'airflow', 'depends_on_past': False, 'start_date': datetime(2023, 3, 1), 'email_on_failure': True, 'email_on_retry': False, 'retries': 1, 'retry_delay': timedelta(minutes=5), } dag = DAG( 'send_email_alert', default_args=default_args, schedule_interval='@once', ) send_email_task = EmailOperator( task_id='send_alert_task', to='', subject='Alert Email from Airflow', html_content='

This is a alert email sent from Airflow.

', dag=dag, ) send_email_task In this example, we’ve defined a DAG called send_email_alert that runs once (schedule_interval='@once') and has a single task called send_email_task. The EmailOperator is used to send the email, and we’ve defined the recipient, subject, and body of the email as arguments to the operator. The recipient parameter is passed from dag run conf parameter. We’ve also specified some default arguments for the DAG like the number of times to retry the task if it fails etc. To run this DAG, you’ll need to have a working SMTP server set up to send the email. You can configure the SMTP server settings in your Airflow configuration file. /opt/airflow/ansible.cfg 1 2 3 4 5 6 7 8 9 10 # If you want airflow to send emails on retries, failure, and you want to use # the airflow.utils.email.send_email_smtp function, you have to configure an # smtp server here smtp_host = smtp.gmail.com smtp_starttls = True smtp_ssl = False smtp_user = your gmail id # smtp_password = your gmail password smtp_port = 25 smtp_mail_from = give the email, from which email id you want send the mails(your mail id ) Process Command Stream and trigger DAG Event streams need to be consumed by a Dispatcher (Kafka Consumer) which knows how to process an incoming event or action. In this case, a dispatcher decides which event workflow DAG needs to be triggered based on the incoming events. The dispatcher should be able to talk to Airflow and trigger the appropriate DAG. We will use the Airflow HTTP API to trigger the DAG run. Following is an example python dispatcher code, 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 from confluent_kafka import Consumer from confluent_kafka.serialization import StringDeserializer from confluent_kafka.schema_registry import SchemaRegistryClient from confluent_kafka.schema_registry.avro import AvroDeserializer import json import argparse def read_ccloud_config(config_file): conf = {} with open(config_file) as fh: for line in fh: line = line.strip() if len(line) != 0 and line[0] != "#": parameter, value = line.strip().split('=', 1) conf[parameter] = value.strip() return conf def pop_schema_registry_params_from_config(conf): """Remove potential Schema Registry related configurations from dictionary""" conf.pop('schema.registry.url', None) conf.pop('basic.auth.user.info', None) conf.pop('basic.auth.credentials.source', None) return conf if __name__ == '__main__': # Read arguments and configurations and initialize parser = argparse.ArgumentParser(description='Kafka Consumer') parser.add_argument('--config_file', required=True,help='Absolute path to configurations file that contains properties used to configure a Kafka consumer') parser.add_argument('--topic', required=False, help='Kafka topic to consume messages from.') config_file = args.config_file topic = args.topic conf = read_ccloud_config(config_file) schema_registry_conf = { 'url': conf['schema.registry.url'], 'basic.auth.user.info': conf['basic.auth.user.info']} schema_registry_client = SchemaRegistryClient(schema_registry_conf) event_schema = { "type" : "record", "name" : "EventSchema", "namespace" : "event", "fields" : [ { "name" : "command", "type" : "string", "doc" : "Command to process and the DAG to trigger" }, { "name" : "params", "type" : "string", "doc" : "Arguments for event workflow specific DAG" } ], "doc:" : "Schema of example command" } schema_str = json.dumps(event_schema) event_avro_deserializer = AvroDeserializer(schema_registry_client = schema_registry_client, schema_str = schema_str) string_deserializer = StringDeserializer('utf_8') consumer_conf = pop_schema_registry_params_from_config(conf) consumer = Consumer(consumer_conf) while True: try: # SIGINT can't be handled when polling, limit timeout to 1 second. msg = consumer.poll(1.0) if msg is None: continue key = string_deserializer(msg.key()) event_json = avro_deserializer(msg.value(), SerializationContext(msg.topic(), MessageField.VALUE)) if event_json is not None: event_type = event_json["event"] params = json.loads(event_json["params"]) # DAG ID is inferred from the event type value dag_id = event_type.split(".")[1] payload = {"conf": params} # The Authorization is the base64 encoded value of Airflow username and password headers = { "Content-Type": "application/json", "Authorization": "Basic YWRtaW46YWRtaW4=" } dag_run = requests.post(f'http://localhost:8080/api/v1/dags/{dag_id}/dagRuns', data=json.dumps(payload), headers=headers) dag_response = dag_run.json() print(dag_response) except KeyboardInterrupt: pass finally: # Leave group and commit final offsets consumer.close() The dag_id should be dynamically inferred from the event message based on the schema followed to maximise the range of dags covered using a single dispatcher and automate the process. In this example, the dag_id is inferred from the command column of the event message. For example, if command is app.send_email_alert, the DAG id is assumed to be send_email_alert . Run the above python code with topic and config file as arguments, 1 python dispatcher.py --topic event_topic --config_file kafka_server.config The triggered DAG and its status can be viewed in the UI. Conclusion In conclusion, we can build robust, scalable, and flexible event workflows in Apache Airflow and trigger them by processing commands from Apache Kafka in real time. Kafka allows you to stream events from various sources and distribute them to multiple consumers, while Airflow provides a flexible framework for orchestrating the processing of these events using event-specific DAGs. With Airflow’s built-in monitoring and alerting capabilities, you can easily track the progress of your pipelines and receive notifications if anything goes wrong. Overall, using Kafka and Airflow together can help to streamline your event processing workflows and improve your data processing capabilities. --- # Kafka batch processing with Airflow URL: https://platformatory.io/blog/Kafka_batch_processing_with_Airflow/ Published: 2023-03-24 Authors: Ashwin Venkatesan Categories: Kafka, Data Engineering, Workflow Orchestration Introduction In the world of big data, managing large datasets is crucial. Batch processing is the process of running a large set of data through a particular program or pipeline at one time. In this blog post, we will discuss how Kafka and Airflow can be used for batch processing. Kafka is a distributed streaming platform which uses logs as the unit of storage for messages passed within the system. Kafka has a unique architecture that allows it to handle high volume data streams in real-time. Event streaming enables real time data interpretation and processing to effect near real time decisions to improve efficiency and optimize costs in businesses. Kafka offers a distributed, highly scalable, elastic, fault-tolerant, and secure infrastructure for real time event streams. Kafka is used in a wide variety of use cases like processing real time transactions in banks, real time analysis of sensor data from IoT devices etc. Airflow is an open source orchestration tool to manage big data workflows. Workflows are programmatically authored as Directed Acyclic Graphs (DAGs) of tasks. The Airflow scheduler executes your tasks on an array of workers while following the specified dependencies. Airflow pipelines are defined as Python code, which means that anything that you can do with Python you can do with Airflow. It also provides a variety of operators and hooks which helps us to integrate seamlessly with most of the cloud and open-source services. Airflow is designed as a configuration-as-a-code system and it can be heavily customized with plugins. Why Airflow in Batch processing pipeline? Although real time stream processing is used with Kafka mostly, there are a lot of instances where batch processing is required. For example, Online stores might be interested in finding out the hourly or daily aggregate of the number of unique users arriving through a particular advertising channel to optimise their ad spends. Banks settling the accumulated bills to vendors at the end of day based on daily transactions. Airflow is an ideal tool to orchestrate and manage batch processing of logs from Kafka topics as it run on schedules, so the resource usage is significantly lower when compared to Kafka streams or any streaming application. Airflow allows us to decouple big tasks into smaller ones and manage the dependencies between them using DAGs. It also allows us to monitor the status of tasks, re-run or restart tasks from any given point in a workflow in case of failure. Airflow also lets you integrate with tools like Apache Spark etc. to execute the task. Kafka consumer partition assignment strategy In general, Kafka consumers are identified by a consumer group id i.e. all the consumer having the same group id will share the subscribed TopicPartitions among them. When a consumer is added or removed from the group, a consumer re-balance is triggered which completely reassigns TopicPartitions among the new set of consumers. There is no guarantee that the consumer-partition mapping will remain the same before and after re-balance. To read about more on the different partition assignment strategies, please visit this link. To control the consumer-partition mapping, we need to manually assign a TopicPartition to a consumer in the group. This can be achieved by using consumer.assign() command. Manual partition assignment can be useful in cases where different processing logic are applied for different partitions, assigning dedicated consumers to heavy throughput partitions etc. In this example, we will use consumer.assign to consume from a specific partition, process the data and produce the values to the same output topic partition as input topic. Airflow Dynamic Task Mapping Dynamic task mapping enables us to create parallel tasks in DAG at run time. It facilitates running parallel tasks equal to the number of input Kafka topic partitions. In Kafka, maximum parallelisation is defined by the number of topic partitions. The expand() command is used to dynamically map tasks in Airflow. For more information, visit this link. We will use manual partition assignment with consumers rather than group based partition assignment. This is to ensure that data can be consumed from an input topic partition, processed and produced to an output topic partition same as the input topic partition in parallel tasks. For the above logic to hold true, the input and output topic should be created with the same number of partitions. Consumer re-balancing in group based partition assignment can lead to mix up while processing data in parallel tasks. Step 1: Download and setup Airflow For this tutorial purposes, we will run airflow in docker. For Production, Airflow supports helm charts for Kubernetes deployment. We will be following this link to set up Airflow in docker. Open a terminal window and navigate to the working directory. 1 cd airflow_kafka Fetch the docker-compose.yml file, 1 curl -LfO   'https://airflow.apache.org/docs/apache-airflow/2.3.2/docker-compose.yaml' Create the required folders for docker compose and set the airflow uid (for Linux), 1 2 mkdir -p ./dags ./logs ./plugins ./results echo -e "AIRFLOW_UID=$(id -u)" > .env We have created an extra folder called results to store topic offset locally. Next, we need Kafka python libraries which are not available in the default airflow image. So, let’s build our custom image with the required dependencies, Create a requirements.txt file with the required packages, 1 confluent-kafka Create a Dockerfile to build custom image, 1 2 3 4 5 6 7 8 9 10 11 FROM apache/airflow:2.3.0 USER root RUN apt-get update \ && apt-get install -y --no-install-recommends \ vim \ && apt-get autoremove -yqq --purge \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* USER airflow COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt In docker-compose.yml, comment the image option and comment out the build option, 1 2 3 4 5 6 7 8 9 10 version: '3' x-airflow-common: &airflow-common # In order to add custom dependencies or upgrade provider packages you can use your extended image. # Comment the image line, place your Dockerfile in the directory where you placed the docker-compose.yaml # and uncomment the "build" line below, Then run `docker-compose build` to build the images. # image: ${AIRFLOW_IMAGE_NAME:-apache/airflow:2.3.0} build: . environment: ...... Also, add results to the docker container volumes, 1 2 3 4 5 volumes: - ./dags:/opt/airflow/dags - ./logs:/opt/airflow/logs - ./plugins:/opt/airflow/plugins - ./results:/opt/airflow/results Run database migrations and create the first user account, 1 docker-compose up airflow-init Now the Airflow is set up and can be started by executing, 1 docker-compose up -d Airflow web UI can be accessed at http://localhost:8080/ Step 2: Setup the Kafka Server config file Before we start writing dags, let’s create the config file to access the input topic in a Kafka cluster. This tutorial assumes you have basic Kafka knowledge and already have an input Kafka topic set up in a remote or local Kafka cluster. Here, we will use an existing topic in the Confluent Cloud as the input topic. The client config file to connect to Kafka cluster will look like the following, kafka_server.config 1 2 3 4 5 bootstrap.servers=: security.protocol=SASL_SSL sasl.mechanisms=PLAIN sasl.username= sasl.password= In addition to the above, we can also define producer and consumer specific properties. It would be ideal to have separate config files for producer and consumer. Place the kafka_server.config file inside the plugins folder to make it available inside the container. The input topic here contains the following as message value, 1 2 3 4 {  "datetime": "23/12/2006 16:52:00", "voltage": 239.94 } Step 3: Define DAG parameters Let’s create the dag.py inside the /dags folder. Airflow automatically reads dags defined in the /dags folder. Import the required modules, 1 2 3 4 5 6 7 8 9 10 from datetime import datetime, timedelta import os import pendulum import pandas as pd import csv import json from confluent_kafka import Consumer, TopicPartition, Producer from confluent_kafka.serialization import StringSerializer from confluent_kafka.admin import AdminClient from airflow.decorators import dag, task Function to read and parse the config file, 1 2 3 4 5 6 7 8 9 10 11 12 def read_ccloud_config(config_file): """Read Confluent Cloud configuration for librdkafka clients""" conf = {} with open(config_file) as fh: for line in fh: line = line.strip() if len(line) != 0 and line[0] != "#": parameter, value = line.strip().split('=', 1) conf[parameter] = value.strip() return conf A producer callback function to print the delivered status, 1 2 3 4 5 6 7 8 9 10 11 12 13 14 delivered_records = 0 # Callback function when a message has been successfully delivered def acked(err, msg): global delivered_records """Delivery report handler called on successful or failed delivery of message """ if err is not None: print("Failed to deliver message: {}".format(err)) else: delivered_records += 1 print("Produced record to topic {} partition [{}] @ offset {}" .format(msg.topic(), msg.partition(), msg.offset())) Define the global variables to be used in the dag tasks and the dag configurations. The input values are hard-coded in this example. The input values can be given while triggering the dag as input parameters as well. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 # Input Values topic_config_file = "/opt/airflow/plugins/kafka_server.config" topic_name = "airflow-input-topic" output_topic_name = "airflow-output-topic" # Local file to save latest offsets for topic partitions local_offset_file = "/opt/airflow/results/topic-offsets-latest.csv" consumer_conf = read_ccloud_config(topic_config_file) producer_conf = read_ccloud_config(topic_config_file) # Create an empty csv file with headers if not available if not os.path.exists(local_offset_file): with open(local_offset_file, "w+") as file: csvwriter = csv.writer(file) csvwriter.writerow(["id", "topic", "partition", "last_offset"]) # Define the DAG configuration for the DAG() function with the @dag decorator, @dag( dag_id="{}_batch_processor".format(topic_name), schedule_interval='@daily', start_date=pendulum.datetime(2022, 5, 1), catchup=False, dagrun_timeout=timedelta(minutes=60), ) def DAG(): The config catchup=False is set up to avoid DAG to run missed scheduled runs. Step 4: Fetch partition ids for the given topic Let’s start building the DAG by defining each sequential task. All the tasks should be defined inside the DAG() function with @task decorator. Initial task is to fetch the partition ids for the given topic, 1 2 3 4 5 6 7 8 9 10 def DAG(): @task def get_topic_partitions(): kadmin = AdminClient(conf) partitions = kadmin.list_topics(topic=topic_name).topics[topic_name].partitions partition_ids = [] for partition in partitions: partition_ids.append(partition) # print(partition_ids) return partition_ids Kafka Admin Client is used to fetch the topic partitions. Step 5: Consume new data for each partition Next task is to consume the message for each given topic partition till the latest offset from the previously committed offset. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 @task def consume_from_topic_partition(partition_id): consume_skip = False # Transient file to store the consumed messages filename = "/opt/airflow/results/raw/%s_%s.csv" % (topic_name, partition_id) if not os.path.exists(filename): with open(filename, 'a+') as csvfile: csvwriter = csv.writer(csvfile) csvwriter.writerow(["key", "datetime", "voltage", "offset"]) # Setup consumer related config consumer_conf["auto.offset.reset"] = "earliest" consumer_conf["group.id"] = "airflow-group" consumer = Consumer(consumer_conf) # Get the earliest and latest offset for a topic partition low, high = consumer.get_watermark_offsets(TopicPartition(topic_name, partition_id)) high_offset = high - 1 print(high_offset) # Load the local offset file as dataframe local_offset_db = pd.read_csv(local_offset_file, index_col=[0]) last_offset_row = local_offset_db.loc[(local_offset_db["topic"] == topic_name) & (local_offset_db["partition"] == partition_id), ["last_offset"]] if len(last_offset_row) == 0: # If the row for the topic partition does not exist, create one. with open(local_offset_file, "a+") as csvfile: csvwriter = csv.writer(csvfile) csvwriter.writerow(["%s_%s" % (topic_name, partition_id) , topic_name, partition_id, 0]) consumer.assign([TopicPartition(topic_name, partition_id, low)]) else: last_offset_value = last_offset_row["last_offset"].values[0] # Skip consumer if last committed offset is the same as latest offset as now new messages to consume if last_offset_value == high_offset: consume_skip = True consumer.assign([TopicPartition(topic_name, partition_id, last_offset_value + 1)]) if consume_skip: print("Already consumed till latest offset") consumer.close() else: total_count = 0 try: while True: msg = consumer.poll(1.0) if msg is None: # No message available within timeout. # Initial message consumption may take up to # `session.timeout.ms` for the consumer group to # rebalance and start consuming print("Waiting for message or event/error in poll()") continue elif msg.error(): print('error: {}'.format(msg.error())) else: total_count += 1 value = json.loads(msg.value()) value["datetime"] = datetime.strptime(value["datetime"], "%d/%m/%Y %H:%M:%S") value["voltage"] = float(value["voltage"]) with open(filename, 'a') as csvfile: csvwriter = csv.writer(csvfile) csvwriter.writerow([msg.key(), value["datetime"], value["voltage"], msg.offset()]) # Break loop if message offset is the latest offset if msg.offset() == high_offset: break except KeyboardInterrupt: pass finally: print(total_count) # Leave group and commit final offsets consumer.close() return partition_id, high_offset Step 6: Commit latest offset for each topic partition locally Next task is to commit the latest consumed offset to the local offset file. Partition Id and latest offset are taken as input from the previous task. Partition ids are passed to the next task. 1 2 3 4 5 6 7 8 9 10 11 @task def commit_offsets_locally(partition_offset_values): partition_ids = [] local_offset_db = pd.read_csv(local_offset_file, index_col=[0]) for value in partition_offset_values: print(value) partition_ids.append(value[0]) local_offset_db.loc[(local_offset_db["topic"] == topic_name) & (local_offset_db["partition"] == value[0]), "last_offset"] = value[1] local_offset_db = local_offset_db.sort_index() local_offset_db.to_csv(local_offset_file) return partition_ids Step 7: Aggregate values for each partition Next task is to aggregate the values for the consumed messages. We will calculate the average voltage for each unique date and store them in a transient processed-csv file. 1 2 3 4 5 6 7 8 @task def process_topic_messages(partition_id): messages_db = pd.read_csv("/opt/airflow/results/raw/%s_%s.csv" % (topic_name, partition_id), parse_dates=["datetime"]) daily_voltage_avg = messages_db[["datetime", "voltage"]].set_index("datetime").groupby(pd.Grouper(freq='D')).mean().reset_index() daily_voltage_avg.columns = ["date", "avg_voltage"] # Store in a transient processed file daily_voltage_avg.to_csv("/opt/airflow/results/processed/%s_%s.csv" % (topic_name, partition_id)) return partition_id Step 8: Produce aggregated value to output topic Next task is to produce the aggregated values to the output topic. Date wise average voltage values are produced to the same partition as the input topic. So, the input and output topics are co-partitioned. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 @task def produce_processed_data_to_output_topic(partition_id): # Add producer related configuration producer_conf['key.serializer'] = StringSerializer('utf-8') producer_conf['value.serializer'] = StringSerializer('utf-8') p = Producer(producer_conf) with open("/opt/airflow/results/processed/%s_%s.csv" % (topic_name, partition_id), 'r') as file: reader = csv.reader(file) for row in reader: if 'date' in row: continue p.poll(0) record_key = row[1] record_value = json.dumps({"date": str(row[1]), "voltage": row[2]}) p.produce(output_topic_name, key=record_key, value=record_value, partition=partition_id, on_delivery=acked) p.flush() return "Finished producing" Step 9: Define the task flow for the DAG Next step is to connect the defined tasks in the appropriate order for the dag to execute. The expand() command is used to execute tasks in parallel and simultaneously. 1 2 3 4 partitions_latest_offset_list = consume_from_topic_partition.expand(partition_id=get_topic_partitions()) partitions_list = commit_offsets_locally(partitions_latest_offset_list) partitions_list = process_topic_messages.expand(partition_id=partitions_list) produce_processed_data_to_output_topic.expand(partition_id=partitions_list) Finally, call the DAG() function to execute the dag. 1 dag = DAG() Executing the dag does not trigger the dag. A dag is triggered based on the defined schedule and can also be triggered manually in web UI and rest API endpoint. Now, run the docker-compose up -d  command and head to the link http://localhost:8080/. Default username and password for the airflow web UI are, 1 2 Username: airflow Password: airflow Once you log in, you should be able to see the defined DAG in the web UI which should have the same name as the dag_id we defined in the DAG configuration. We can now trigger the airflow-input-topic_batch_processor by clicking the play button under the Actions section. We can track the dag status in Graph or Grid mode in the dag page. Also, we can see the Logs, XCom etc. for each dag task like below. Conclusion In this tutorial, we were able to do the following, Build custom Airflow docker image with required python dependencies. Run Airflow in docker compose with a custom docker image. Dynamic task mapping in Airflow to run parallel tasks. Produce to and consume from a Kafka topic per partition. Input and Output Kafka topics are co-partitioned. In conclusion, Kafka and Airflow are two of the most popular open-source tools that are used for batch processing. Kafka is designed to handle high-volume data streams in real-time, while Airflow is designed to orchestrate complex workflows and data processing pipelines. Using Kafka and Airflow together can provide a scalable and fault-tolerant solution for batch processing large datasets. References https://airflow.apache.org/docs/apache-airflow/2.3.0/start/docker.html https://airflow.apache.org/docs/apache-airflow/2.3.0/concepts/dynamic-task-mapping.html https://airflow.apache.org/docs/docker-stack/build.html https://github.com/confluentinc/examples/tree/7.1.0-post/clients/cloud/python --- # Faust 101 - Stream processing URL: https://platformatory.io/blog/Faust_101/ Published: 2023-03-17 Authors: Ashwin Venkatesan Categories: Stream Processing, Kafka, Python Introduction Stream processing is a data processing technique to analyze, aggregate, filter or enhance a continuously ingested data as they come. Stream processing is used synonymously with real time data processing as the input data is processed as they are ingested with minimal latency. Some of its applications include fraud detection, IoT device data streaming, event streaming etc. Stream processing involves a publisher / source which generates data to a stream processing application where the data is processed, and the results sent to a subscriber / sink. Kafka Streams is one of the best streaming applications to do distributed real time stream processing. Although it’s a great tool to do real time stream processing, actually setting up a production level stream processing pipeline is not an easy task. There is a learning curve associated with designing effective Kafka Streams Applications. Kafka Streams API is mainly written in Java and Scala but there are python implementations like Faust which can also be used. What is Faust? Faust is a stream processing library written in Python which uses the capabilities of Kafka Streams underneath. It is used at Robinhood to build high performance distributed systems and real-time data pipelines that process billions of events every day. The original repo which has around 6.5k stars is currently deprecated but it has been forked and actively maintained by community. For reliability Faust uses a Kafka topic as “write-ahead-log”. Popular libraries like Pandas, NumPy, SQL Alchemy etc. can be used in conjunction with Faust. It uses a superfast embedded database (written in C++) called RocksDB to store states during stream processing. Following are the concepts used by Faust, App - an instance of the Faust application. Agent - an asynchronous, distributed processor to process continuous data. Table - sharded dictionaries to enable stateful stream processing. Channel - a buffer/queue used to send and receive messages. Sensors - To monitor and record events in the Faust application. Faust stores internal data like application configurations, table data etc. in Kafka topics to facilitate distributed, fault-tolerant and durable data processing across machines. In general, Faust inputs data from topics, process it and write output to topic again. Faust supports all the operations like group by, map, filter, joins etc. which are supported by Kafka Streams. Faust vs Kafka Streams Some of the key differences between Faust and Kafka Streams are as follows: Faust is written in Python, while Kafka Streams is written in Java. Python has better support for data engineering and machine learning libraries like Pandas, Scikit-learn etc. which can be effectively utilized by Faust. Kafka Streams uses a Domain Specific Language(DSL) whereas Faust is just Python. Faust provides a simpler, higher-level API that is easier to use than Kafka Streams’ lower-level API. If you are new to stream processing or prefer a simpler API, Faust may be a better choice. The concept of “agents” comes from the actor model, and means the stream processor can execute concurrently on many CPU cores, and on hundreds of machines at the same time. Thanks to Faust and asyncio you can now embed your stream processing topology into your existing asyncio/ eventlet/Twisted/Tornado applications. No need for complex topologies as it can be simplified with just python. Both Kafka Streams and Faust are tightly integrated with Kafka and can leverage Kafka’s features such as availability, concurrency and fault tolerance. In essence, Faust is a good starting point for anyone who wants to learn how Kafka stream processing systems work. It is a better option for data analytics or data science use cases. Prerequisites Our objective here is to write a simple Kafka streams application in python using the Faust package. We will leverage the Confluent cloud infrastructure to create some topics. Confluent provides a fully managed cloud service for Apache Kafka which is super easy to deploy and use. You can sign up for Confluent cloud here and earn free credits worth $400 for the first 60 days. For this tutorial purposes, we will be using an open-source time-series based power consumption dataset which is available in Kaggle. Measurements in the dataset are of electric power consumption in one household with a one-minute sampling rate over a period of almost 4 years. We will look at only the voltage parameter and find its average for every 1-hour windows. These windowed averages can tell us if there is a power spike which needs to be looked at. Step 1: Create a topic in Confluent Cloud Once you have signed up for a confluent cloud account, you can create a basic cluster with default configuration at the region of your liking. Navigate to topics and create a topic with default configurations called voltage_input. Step 2: Downloading and installing requirements Let’s create a python client to produce data to the topic. Navigate to ‘Clients’ under the ‘Data integration’ option on the cluster dashboard and create a new python client. Generate api key and copy the configuration snippet. Save it in the following path, 1 $HOME/.confluent/python.config We will use the confluent-kafka python package to produce data to the input topic from local. Create a virtual environment with the following packages, requestscertifi confluent-kafka[avro,json,protobuf]>=1.4.2 faust[fast] Let’s download the python file which will read the config file and parse it for the application to use. 1 wget https://raw.githubusercontent.com/confluentinc/examples/6.1.1-post/clients/cloud/python/ccloud_lib.py Download the dataset file household_power_consumption.txt from the Kaggle link and save it in our working directory. Step 3: Produce to the input topic We will use the ccloud_lib python module to parse the config file and also the input arguments for the producer module. producer.py 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 #!/usr/bin/env python import json import ccloud_lib delivered_records = 0 # Callback function when a message has been successfully delivered def acked(err, msg): global delivered_records """Delivery report handler called on successful or failed delivery of message """ if err is not None: print("Failed to deliver message: {}".format(err)) else: delivered_records += 1 print("Produced record to topic {} partition [{}] @ offset {}" .format(msg.topic(), msg.partition(), msg.offset())) def fetch_time_series_data(count=1): data_split = data[count].split(";") try: new_message = {"datetime": datetime.strptime(data_split[0] + " " + data_split[1], "%d/%m/%Y %H:%M:%S"), "voltage": float(data_split[4])} except ValueError: new_message = {"datetime": datetime.strptime(data_split[0] + " " + data_split[1], "%d/%m/%Y %H:%M:%S"), "voltage": 0.0} return count+1,new_message if __name__ == '__main__': # Read arguments and configurations and initialize args = ccloud_lib.parse_args() config_file = args.config_file topic = args.topic conf = ccloud_lib.read_ccloud_config(config_file) # Create topic if needed # ccloud_lib.create_topic(conf, topic) # Initialize the producer configuration producer_conf = ccloud_lib.pop_schema_registry_params_from_config(conf) producer_conf['key.serializer'] = StringSerializer('utf-8') producer_conf['value.serializer'] = StringSerializer('utf-8') p = SerializingProducer(producer_conf) with open("./household_power_consumption.txt", "r") as f: data = f.readlines() no_of_records = 10000 start_index = 0 while no_of_records: # Call poll to send any queued record p.poll(0) start_index,base_message = fetch_time_series_data(start_index) no_of_records -= 1 value = base_message record_key = "power" record_value = json.dumps(value) p.produce(topic, key=record_key, value=record_value, on_delivery=acked) # Call flush to send any queued record at the end p.flush() We are producing the voltage data with a datetime column to the input topic. poll() or flush() needs to be called to send the queued data to the Kafka broker. Step 4: Creating a Faust app Let’s create a simple Faust app which will read from the voltage_input topic and do a windowed aggregation of the voltage values. First, we need to define the input and output data models for the Faust app. 1 2 3 4 5 6 7 8 9 10 # Input model class PowerModel(faust.Record, coerce=True, date_parser=parse_date): datetime: datetime voltage: float #Output model class AverageVoltage(faust.Record): start_time: datetime count: int mean: float Let’s initialize the faust app with the kafka broker connection details. We need to pass in the SASL credentials which were created previously and stored in the config file. 1 2 3 4 ssl_context = ssl.create_default_context() ssl_context.load_verify_locations(cafile=certifi.where()) app = faust.App('myapp', broker='kafka://BROKER_HOST_NAME:9092', broker_credentials=faust.SASLCredentials(username=SASL_USERNAME, password=SASL_PASSWORD, ssl_context=ssl_context), topic_replication_factor=3, topic_partitions=3) Define the input topic stream and output sink topic for the aggregated average voltages. 1 2 voltage_stream = app.topic('voltage_input', key_type=str, value_type=PowerModel) sink = app.topic('voltage_avg', value_type=AverageVoltage) Next, we need to define the aggregation logic for calculating the hourly average voltage. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 def hourly_window_processor(key, events): timestamp = key[1][0] timestamp = datetime.fromtimestamp(timestamp) values = [event.voltage for event in events] count = len(values) mean = sum(values) / count logger.info( f'processing window:' f'{len(values)} events,' f'mean: {mean:.2f},' f'timestamp {timestamp}', ) sink.send_soon(key='avg_voltage_hourly', value=AverageVoltage(start_time=timestamp, count=count, mean=mean)) hourly_window_voltage = app.Table('hourly_average_voltage', default=list, partitions=3, on_window_close=hourly_window_processor)\ .tumbling(timedelta(hours=1), expires=30)\ .relative_to_field(PowerModel.datetime) We are using a tumbling window here as we need to calculate the average every hour. Values are stored in the transition table hourly_average_voltage as it comes. Once the time window closes, the callback function calculates the average for the values in that window and sinks it to the output topic. Now, we need to define an app agent to append the input data stream to the hourly window voltage table. 1 2 3 4 5 6 @app.agent(voltage_stream) async def processor(records): async for record in records: value_list_hour = hourly_window_voltage['events'].value() value_list_hour.append(record) hourly_window_voltage['events'] = value_list_hour Following is the final aggregate code of the faust app, app.py 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 import faust from datetime import datetime, timedelta from dateutil.parser import parse as parse_date import ssl import certifi import logging logger = logging.getLogger(__name__) ssl_context = ssl.create_default_context() ssl_context.load_verify_locations(cafile=certifi.where()) class AverageVoltage(faust.Record): start_time: datetime count: int mean: float class PowerModel(faust.Record, coerce=True, date_parser=parse_date): datetime: datetime voltage: float app = faust.App('myapp', broker='kafka://pkc-7prvp.centralindia.azure.confluent.cloud:9092', broker_credentials=faust.SASLCredentials(username="3TCIKXFSRGTFZCMV", password="7OUQQoTN6zIA2gS5LK/hrAxQjpRjIhw+w9+/gdoUJZT+8vlPxEtKkJ+n+X1cPkpm", ssl_context=ssl_context), topic_replication_factor=3, topic_partitions=3) app.conf.table_cleanup_interval = 1.0 voltage_stream = app.topic('test3', key_type=str, value_type=PowerModel) sink = app.topic('voltage_avg', value_type=AverageVoltage) def hourly_window_processor(key, events): timestamp = key[1][0] timestamp = datetime.fromtimestamp(timestamp) values = [event.voltage for event in events] count = len(values) mean = sum(values) / count logger.info( f'processing window:' f'{len(values)} events,' f'mean: {mean:.2f},' f'timestamp {timestamp}', ) sink.send_soon(key='avg_voltage_hourly', value=AverageVoltage(start_time=timestamp, count=count, mean=mean)) hourly_window_voltage = app.Table('hourly_average_voltage', default=list, partitions=3, on_window_close=hourly_window_processor)\ .tumbling(timedelta(hours=1), expires=30)\ .relative_to_field(PowerModel.datetime) @app.agent(voltage_stream) async def processor(records): async for record in records: value_list_hour = hourly_window_voltage['events'].value() value_list_hour.append(record) hourly_window_voltage['events'] = value_list_hour if __name__ == '__main__': app.main() Step 5: Running the app and viewing the results We can start the Faust worker in a terminal by executing the following command, 1 python app.py worker -l info Let’s open another terminal and start producing records to the voltage_input topic by executing the following command. 1 ./producer.py -f ~/.confluent/python.config -t test1 Let’s write a simple consumer.py code to consume the aggregated results from our output topic voltage_avg. consumer.py 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 from confluent_kafka import Consumer import json import ccloud_lib import sys import datetime if __name__ == '__main__': # Read arguments and configurations and initialize args = ccloud_lib.parse_args() config_file = args.config_file topic = args.topic conf = ccloud_lib.read_ccloud_config(config_file) # Create Consumer instance with a unique group id # 'auto.offset.reset=earliest' to start reading from the beginning of the # topic if no committed offsets exist consumer_conf = ccloud_lib.pop_schema_registry_params_from_config(conf) consumer_conf['group.id'] = 'python_example_group_1' consumer_conf['auto.offset.reset'] = 'earliest' consumer = Consumer(consumer_conf) # Subscribe to topic consumer.subscribe([topic]) # Process messages total_count = 0 try: while True: msg = consumer.poll(1.0) if msg is None: print("Waiting for message or event/error in poll()") continue elif msg.error(): print('error: {}'.format(msg.error())) else: # Check for Kafka message record_key = msg.key() record_value = msg.value() data = json.loads(record_value) total_count += 1 print(data) except KeyboardInterrupt: pass finally: # Leave group and commit final offsets consumer.close() Run the following command to start the consumer in terminal, 1 ./consumer.py -f ~/.confluent/python.config -t voltage_avg Now, you can view the magic by opening three terminals and running the producer, Faust app worker and consumer simultaneously in them. Conclusion In this tutorial, we were able to accomplish the following, Create a simple Faust application to calculate hourly windowed average of voltages from our input dataset. Create a simple python producer and consumer to interact with a Confluent cloud topic. Faust is great way to leverage the capabilities of Kafka Streams in conjunction with popular python libraries like Pandas, NumPy, Scikit-learn etc. to write distributed, fault-tolerant streaming applications. Faust is simple and can be used to build real-time applications involving machine learning, deep learning etc. Some of the other python coded stream processing library include, https://github.com/wintoncode/winton-kafka-streams https://github.com/bytewax/bytewax https://github.com/rh-marketingops/fluvii References https://faust.readthedocs.io/en/latest/userguide/tables.html https://github.com/robinhood/faust/blob/master/examples/windowed_aggregation.py https://github.com/confluentinc/examples/tree/7.1.0-post/clients/cloud/python --- # Building whatever (X) as a service: XaaS URL: https://platformatory.io/blog/SaaS-architecture-primer/ Published: 2023-03-03 Authors: Pavan Keshavamurthy Categories: SaaS, Platform Engineering, API Management Architecture isn’t dead Founders have a lot on their hand. Even seasoned engineering leaders struggle with the dilemma of choices when the primary pressure is the market opportunity and everything is hinged on time to ship. Technical debt is pretty much the state of affairs. Architecture thinking might be frowned upon or looked at as unrealistic. It is true that, “architecture upfront” is a red herring, particularly at early stage, in a volatile setting. Nonetheless, we can’t stress enough about the importance of a north star vision and guard rails even in evolving architectures. Truly emergent architectures don’t just emerge organically. Rather the most successful ones are almost always the result of good principles chosen with careful deliberation. Everything is a tenancy problem. The SaaS economy is fueled by multi-tenancy. The more, the merrier. However, this spawns its own set of issues. Even the most mature SaaS companies struggle with these problems: Noisy Neighbours: Likely to degrade performance for others Freeloaders: doing more than what they should be, at their pricing tier Under-utilizers: not getting enough bang for buck. Churn risk The reality is that “pay for only what you use” is notoriously difficult to implement in practice, as it puts a huge amount of pressure on what to meter, thus spawning notoriously difficult to understand (and unpredictable) billing models. No wonder many SaaS companies end up pricing their solutions with a tenant quota around a facade of some business value, while many still struggle ending up passing infrastructure tiered offerings. In our own working experience, we have seen even mature, hyperscale SaaS providers struggle to understand usage patterns and fairness of their billing models. The other side of the same problem is a fin-ops one, of cost attribution of compute and infrastructure resources, relative to pricing subscribed. The least you must do is to start with the following fin-ops principles: Price the solution to the customer around the most self-evident business metric (aka consumption units). This must make sense! Occam’s Razor applies. Meter and measure these with the most granular labels possible Consider tenancy and clustering assumptions carefully: Be in a position to hold up customer usage (measured in consumption units) against an aggregate metric of your underlying cost (measured in internal cost units) The above constitute an exchange rate that must provide a clearer picture of your economics Don’t reinvent the wheel - build on great platform primitives Tech-choices are hard, our biases notwithstanding. Unless you’re building specifically for a totally different class of problems, you’re likely to be building on the public cloud. While cloud providers seek to provide differentiated offerings, there is a risk of lock-in. Don’t get us wrong – there are very many benefits in these offerings and the vertically integrated experience provided by the hyperscaler is very compelling; However, it does decrease your leverage in potentially migrating elsewhere when push comes to shove. This is also materially significant for those building with a multi-cloud, hybrid-cloud offering in the first place. It makes eminent sense to balance such risks pragmatically. Standardize on mature open-source Adopt ubiquitous tools, that have become platform interfaces by themselves Adopt something conforms to both the above, with a managed service provided by the cloud (as opposed to a completely proprietary offering) BYOC is critical in a multi-cloud hybrid-cloud landscape Based on the nature of your product, markets you want to cater to and your tenancy model, you must consider Whether your solution may ever need to be deployed outside your choice of cloud provider (including on-premise, ex: for regulated domains) Data sovereignity and legal considerations for markets you cater to If a cloud provider marketplace could itself be a GTM channel In all these models, it makes sense to think about tenanting the customer around clusters of availability, along with freedom to choose the cloud provider. For sufficiently complex products, a control-plane data-plane separation of concerns clearly emerges; And although a cloud provider choice for a control plane need not be within customer discretion, it would most times make sense for the control plane to be colocated in the same provider. Finally, hybrid cloud is a reality. If you need to support on-premise, the most unreasonably effective way is to standardize on Kubernetes as the underlying chassis, an architecture choice that would work resonate with all the other points we’ve made. Think ecosystems The maker’s mind is fundamentally creative. There is always an urge to capture the greatest part of the value chain. However, one must weigh the costs, efforts and the RoI of building (and overreaching in the process); The SaaS offering is fundamentally centred around owning the critical path of some user experience around a business problem. A PaaS offering is centred around the developer experience of a specific technology. No matter what the tierage of your offering is, there will always likely be areas which could be catered to by someone else with a (even if marginal) competitive advantage. SaaS companies must therefore be brutally honest about areas that are core, adjacent or peripheral to their business. A partner ecosystem can be a very effective leverage to creating an ecosystem and thus compounding the scale of your own business while improving integration and customer stickiness. It is crucial to think about: Your ecosystem proposition: What is in it for your partners (particularly makers or developers) - typically converging to a revenue sharing goal API Strategy as part of your product, focused around key integrations Extension interfaces through plugins, that run in sandboxed runtimes provided by you (consider Web Assembly) Ecosystem fairness: Ensure you don’t compete for the market share that the partner network competes for --- # The 3 pillars of Platform architecture URL: https://platformatory.io/blog/three-pillars-of-platform-architecture/ Published: 2021-05-31 Authors: Pavan Keshavamurthy Categories: Platform Engineering, Infrastructure, Kubernetes, Kafka, API Management Platform Engineering is a hot topic. There is an optimist’s view: That it can potentially simplify the tech operating model of large, complex organizations. Yet there is also a cynical take: This is no panacea for conway problems. The crucial question is, what even should be extracted into a “platform” boundary? Greedy platforms tend to stifle team autonomy. Loose platforms tend to add little value and more harm anything else. Allow us to provide a take on what we think should be the three most important pillars for a sound platform strategy. Our recommendation is based on real-life experience of enabling platform-led transformations and areas that have proved most conducive for such an operating model, while providing clear, discernible business value. We will also talk through some universal platform building blocks that you must consider. Hybrid Cloud infrastructure platform In the ever evolving cloud landscape, hardware comes cheap and commoditized. While cloud vendors will still seek to differentiate, it is now amply clear that containers are pretty much the standard level of atomicity for any workload. Therefore, the underlying IaaS, at least in theory, is very fungible. This also signals the rise of Kubernetes as a great leveler and making multi-cloud – hybrid-cloud strategies actually viable without rocket surgery. As Kelsey Hightower puts it “Kubernetes is the interface to the cloud”. If there’s one thing K8S has cracked, it is the declarative control plane API model, and by that it ensures that even if a competitor were to emerge, it would begin by baselining itself against the same API standard. We will go out on a limb and make another prediction: in the same spirit of Atwood’s law: Any sufficiently complicated distributed system that can be natively run on Kubernetes will eventually be run as an operator. That means, for those who may need to steer away from managed services for whatever reason, running an operator is very literally the next best thing. We expect K8S will be the chassis for building literally just about anything cloud native in the next 10 years; PaaS vendors will come up with even better and specialized Developer and operator experiences to run K8S-at-the-core apps with lesser hassle. There are naysayers who think K8S is just too complex (there maybe a hint of truth in this even in 2022), but the sheer rate of increasing production workloads going into k8s is obviously data based testimony staring at you in the face that this is hardly as complex as they say it is. This is definitely led by the cloud providers themselves, but there is also a long tail of hybrid cloud compatible K8S distributions (such as VMWare Tanzu, RedHat OpenShift, Rancher, Nirmata, amongst others) that are enabling this. There are discretionary choices available for which flavor of Kubernetes suits you best and the vendor posture is towards K8S not as infrastructure modernization but as the foundational need for modernizing apps in itself; Even capabilities that were seemingly a point of proprietary leverage for public cloud, such as serverless functions have now gained a first class foothold in Kubernetes, allowing product teams to build towards a deployment target that may run on any IaaS, with Kubernetes. Our advice - if you are willing to make some investments towards Kubernetes, it is about time. Do it. It will certainly prove to be a very robust foundation for building higher order platforms. The Data exchange platform As DB sizes grow, it is inevitable that megaliths and monoliths must die; Shared state and data just has practical limits; Services must own data and therefore, enable themselves towards decomposition into smaller parts and distribution. When that happens, the needs for integrations arise. The platform opportunities in integration are no recent discovery. Messaging platforms have been around for decades. In the cloud native world, Enterprise integration patterns may still hold (give or take), but the aforementioned integration technologies no longer make sense for microservices communication. The services get smaller, chattier and desire eventual consistency patterns which these systems suck at, not to mention that they barely lend themselves to distributed, hybrid cloud deployments without being bottlenecks in themselves. There’s a second, larger problem: Data integration. Analytical problem space increasingly converges into the operational (this is a great thing) and therefore real time data integration is a much bigger problem than ever. Traditional big data approaches fail to fulfill the needs of business expectations where time-to-useful-data (whether be it insight, reporting or other analytics) has to be optimized to its bounds. The best way to solve for both,is through embracing Event Driven, Reactive architecture as the de-facto way to architect applications. In this model: Choreography must be preferred over orchestration. Applications and services exchange data through streams: Event stream processing becomes the mechanism to synchronize and process data continuously and consistently. Most integrations can be handled through the same eventing backbone: An event store holds the logstream of events that can be applied (and replayed if necessary) to derive the state of an application Note that this problem has large-scale distributed system underpinnings to it. As it emerges, it is clear that Apache Kafka is the standout winner for event streaming. Its use-cases are myriad: Everything from (S)EDA, event-sourcing, stream processing to data movement. Kafka solves core problems, such as that of exactly once Processing, a brokered, pub-sub API model that offers the highest number of tuning knobs and customizability to fit purpose, first class data persistence for reliable processing and lends itself to global scale, high throughput, ow latency, fault tolerant deployments. Apart from these, Kafka also offers an ecosystem of connectors, stream processing bolt ons and schema management. Most of all, similar to K8S, Apache Kafka’s data plane protocol has emerged as the de facto API standard for brokered eventing. This is evident in that even with Kafka’s emergent competition, such as Azure event hubs, Apache pulsar or the new kid on the block, RedPanda (formerly vectorized.io) – that are innovating in the path of Kafka (in arguably superior ways), there is still conformance and compatibility to the same API protocol. The Kafka based pub-sub streaming model is clearly emerging as the integration & data backbone of the enterprise. Data and eventing mesh like architectures will evolve on top of Kafka as the data plane standard and enable Data Productization that will be owned and stewarded by domains. App and services integrations will on the other hand, leverage changelog streams and increasingly lead to event-sourced architectures with newer Kafka centric API standards (such as AsyncAPI, CloudEvents) being the guardrails. Our advise - if there’s one thing you’d want to do to tame data across the enterprise, consider a platform architecture with a “universal” stream bus like Kafka. This will certainly provide definitive ROI as an operational platform, while unlocking possibilities in real-time analytics, AI/ML and traditional big data processing. The Connectivity platform APIs are the very connective tissue of the modern enterprise. The explosion of services in the SOA era has resulted in the emergence of API Management as a formal discipline, over and above classic integration middleware platforms (such as ESBs); API Platforms focus on API based mediation, composition patterns and policy based controls on security, traffic management and quotas. While API Management has traditionally applied in SOA context, the microservices landscape brings in a different set of challenges than the Northbound-Southbound communication that API gateways traditionally addressed. This is the challenge of inter-service communication or East-West traffic. This is the emerging solution space of service meshes, where the opportunities include the same as that of API gateways and API management (albeit with more intelligent proxy or agent sidecars), but also extending to routing, load balancing, circuit breaking, traffic shifting, mirroring and most of all, observability through tracing across a graph of services. Till date, there have been attempts to converge gateways and service meshes, but in our opinion, the most complete vision towards this is by Kong (and to a lesser extent, Solo.io). Kong offers a service mesh (Kuma - albeit not SMI compatible, uses Envoy as the data plane), an API gateway (nginx in the data plane) and a programmable plugin layer that supports Lua, Golang, Python and JS. While it is unfair to say Kong is in the de-facto standard of it’s category class as Kafka and K8S, we find it the most plausible candidate worthy of that status eventually; Kong’s core concepts reduce to services and upstreams, routes and consumers, which maybe declaratively targeted by plugins. Kong boasts a large ecosystem of plugins and forks (such as mentionable Apisix), support for HTTP2, gRPC on both VMs, as well as K8S (with K8s ingress); Most of all, Kong provides typically an order of magnitude lift in performance vis-a-vis others and this constitutes a very compelling proposition. The coalescence of API gateways and Service meshes has only begun. We predict Envoy based data-planes will become better and more efficient; We will increasingly look at architectures that not only externalize all network level cross cutting concerns (such as security, traffic management, routing) to the ubiquitous Envoy-at-the-core mesh layer, but also see much “smarter” wire level interception capabilities for different technologies, thus enabling sophisticated capabilities around resilience, load balancing and most of all, the API itself as an abstraction. This is only the beginning, but there are several interesting possibilities just in the networking world with eBPF at the core. On the other hand, HTTP/2 is emerging and there is a rebound of RPC protocols (gRPC, Thrift, Dubbo) that provide consistent typing and deep, idiomatic programming language support; Finally, we also recognize heterogeneous API standards emerging (GraphQL, AsyncAPI, CloudEvents to name some) for a variety of use-cases beyond the core request-response oriented REST/SOAP standards that have been prevalent; To address these and other possibilities, if we had to make a choice today - it would almost certainly be Kong. Finally, we must stress that APIs are just endpoints unless bundled together or built to suit use-cases of their audiences (ie, developers); For API Management to mature in an organization (regardless of API gateway or service mesh infrastructure), the curation of API products (or in an even more abstract sense, integration products) is the most important goal. This enables a transformation from APIs as integration endpoints towards APIs being literally, your business as a service. Conclusion There is clearly the emergence of a “k3” platform stack, consisting of Kubernetes, Kafka, Kong. These address respectively, the three most important pillars of an enterprise digital platform strategy - namely, infrastructure, data and APIs. For the discerning CT(I)O or platform engineering leader, the opportunities are vast and the OSS community has a lot to offer. It is important to take note and strategize accordingly. --- # A Platform engineering manifesto URL: https://platformatory.io/blog/platform-engineering-manifesto/ Published: 2021-05-30 Authors: Pavan Keshavamurthy Categories: Platform Engineering, Infrastructure, Kubernetes, Kafka, API Management There are many hot takes on Platform Engineering. There are success stories and there are horror stories. When done well, there is a team topology that enables a “do it like a digital native” operating model. When done not so well, you end up with a mess of 99 problems cherry-picked straight from the CNCF landscape graveyard of tools. As a company that has chosen to ride the trend, our belief is that platform engineering should be considered essential for any tech company operating in a complex domain, basically with the objective of providing a Dev X that helps you scale. Platforms don’t exist in a vacuum; They are grounded ultimately in the reality of business domains and MUST accelerate product engineering teams in their endeavours. To be clear, not everyone needs a platform engineering team in the first place. One is largely justified when the size of the engineering organization exceeds the Dunbar number or atleast a non-trivial problem of scale. Nonetheless, if you do choose to build a platform engineering team, there are 3 key performance indicators to consider in order to measure success. NPS, CSAT from product engineering teams, as a measure of developer experience Usage metrics of the platform products in themselves Coverage of platform concerns and time to first production deployment (for Product teams) Own a platform architecture & platform product vision Everything begins in robust product foundations and an (evolving) architecture vision. Platform teams must own both a product & an architecture charter. The unique requirements of platform products may themselves be driven by unique challenges in the domain (or specifically that of domain centred product engineering teams) and the incumbent IT landscape ProTip: A pareto principle compliant north star vision of a robust platform architecture must think through the following concerns: Smart Infrastructure, Data Integration & APIs. Building tooling and plugins: For the sake of developers, operators and everything in between The platform is a product that is mainly built with engineers in mind. You build it, you run it is ultimately an elusively aspirational operating model. In reality, re-use dictates efficiency and continuous reinvention of the wheel is harmful to productivity, which is almost a side-effect of autonomous but silo’d teams. A platform team topology on the other hand vests a lean, craft-focused engineering team to build specialization across a variety of cross cutting concerns while enabling a well governed tech estate. Such “Platform engineering” teams are suited ideally to building re-usable artefacts and easily adapted tooling for most concerns. Notably, this will include for example: Infrastructure as code modules Golden images (as also other build-time, run-time tooling) Common Build / Deploy (CI-CD) Pipelines Observability & monitoring toolkits Enable shared-services Operations (securely) in a multi-tenant, hybrid cloud enterprise At the heart of enterprise grade operations is really a tenancy problem; Tenancy is really “who shares what in the house”; A platform-based operating model needs to provide mechanisms for housing tenants in dedicated or shared models, based on resource competition (and thus need for isolation), security, availability, compliance and cost requirements. Operating model flexibility should also provide for having resources managed directly via embedded DevOps teams that “build and run” things or shared SRE (or IT/Cloud-ops teams) that takeover this function for several applications or teams. Protip: There is a need for governance as well as potentially cost attribution or chargeback to teams that foot the bill. Specialize in running complex, distributed systems Fully managed services attempt to dumb down details of large scale distributed system, yet many are actually very leaky abstractions. A trade-off of having cloud vendor neutrality is that one must accept the reality of having fully or partially managed services co-existing with fully self-managed ones, particularly when costs become prohibitive either due to scale (or the lack thereof). This poses a dilemma for technology leaders around the operating model fit. There is a defining line of separation between quality platform engineering teams and vanilla (cloud|dev)-ops teams. Platform engineers will need to gain specific expertise in running complex, distributed systems that have become de-facto platform primitives, providing lego-blocks that allow you to build higher order platforms. Platform adoption is ultimately constrained by expertise and therefore it is crucial that platform engineering teams build highly artisanal guilds that can respond to architectural problems in distributed systems and provide a POV on performance, security an d a variety of cross cutting concerns.