<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tomer Guttman on Medium]]></title>
        <description><![CDATA[Stories by Tomer Guttman on Medium]]></description>
        <link>https://medium.com/@tomerguttman27?source=rss-9a3810d92c03------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xiEK2nhNU3G_vcst_GWMzQ.jpeg</url>
            <title>Stories by Tomer Guttman on Medium</title>
            <link>https://medium.com/@tomerguttman27?source=rss-9a3810d92c03------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 23:51:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tomerguttman27/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[WebRTC, Minus the Headache]]></title>
            <link>https://medium.com/ludeo/webrtc-minus-the-headache-40b4fd2ea834?source=rss-9a3810d92c03------2</link>
            <guid isPermaLink="false">https://medium.com/p/40b4fd2ea834</guid>
            <category><![CDATA[ludeo]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[gaming]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[webrtc]]></category>
            <dc:creator><![CDATA[Tomer Guttman]]></dc:creator>
            <pubDate>Sun, 18 Oct 2026 13:09:30 GMT</pubDate>
            <atom:updated>2026-10-18T13:31:56.986Z</atom:updated>
            <content:encoded><![CDATA[<p><em>You press jump at home. The game runs in a data center far away. For that jump to land on time, two computers that can’t even see each other </em>have to connect in the blink of an eye<em>. Here’s how WebRTC pulls it off, in plain English, with a little help from pigeons, a smart toaster and a telephone operator.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*FjzagggDwpfrV6hhLNpnBw.gif" /></figure><h3>What Is WebRTC, and Why Should Gamers Care?</h3><p><a href="https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API">WebRTC</a> is a free, open web standard that’s built into your browser. It lets apps send video, sound and data straight between devices in real time. Google Meet uses it, Discord in the browser uses it, and cloud games like ours use it. And it’s not just for two people: a group call connects many browsers at once, either directly to each other or through a media server in the middle. The idea is simple. The rest of this post explains why it needs so many strange short names.</p><p>RTC stands for Real-Time Communication, and “real-time” is the important part. When you watch a movie online, a five-second delay is no problem. Nobody notices, because the movie only goes one way: your player quietly loads a few seconds ahead, and nobody is waiting for you to react. But on a video call, if your friend hears your joke five seconds late, the joke is dead. And in a game, if your jump arrives five seconds late, you’re dead.</p><p>That’s why WebRTC matters so much to us at <a href="https://ludeo.com/?utm_source=medium">Ludeo</a>. Cloud gaming is one of the things we do: the game runs on a strong computer in the cloud, and you play it in your browser. Sounds simple, right? Not really. Every button you press has to reach the cloud fast, and every picture of the game has to come back fast. In games, slow means you lose. Usually to a 12-year-old.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e8iXhw7ylsTFBPujCZtx_w.png" /></figure><p>The good news? You don’t have to install anything. No plugins, no downloads, no “please install Flash” (if you remember that one, hello, fellow dinosaurs). Let’s see how it works, in three easy parts.</p><h3>Part 1: The Three Building Blocks</h3><p>WebRTC gives developers three main tools in JavaScript. Each one has a clear job, and together they cover almost everything you need.</p><p><a href="https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia"><strong>getUserMedia</strong></a><strong>: camera and microphone.</strong> This tool turns on your camera and microphone. It’s the reason your browser shows that little “Allow this site to use your camera?” pop-up. At <a href="https://ludeo.com/?utm_source=medium">Ludeo</a>, we don’t actually need it: our game server has no camera, so it records the game’s picture and sound instead.</p><p><a href="https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection"><strong>RTCPeerConnection</strong></a><strong>: the connection itself</strong>. This is the part that actually connects you to the other side (the other “peer”). It handles the setup you’ll see in Parts 2 and 3, like the offer, the answer and finding a path, and it keeps everything encrypted. You give it what you want to send (video, sound, or just one of them), and the other side receives it.</p><p><a href="https://developer.mozilla.org/en-US/docs/Web/API/RTCDataChannel"><strong>RTCDataChannel</strong></a><strong>: game controls and other data.</strong> Not everything is video. Sometimes you want to send text, files or game controls. The data channel can send any data you like, using the same connection. For games, this is perfect: you can send “player pressed jump” with almost no delay. You can even decide if messages must arrive in the right order, or if it’s OK to lose a few to stay fast.</p><p><em>One more fun fact: everything in WebRTC is encrypted, always. You can’t turn it off, even if you ask nicely.</em></p><p>So how does it all travel? WebRTC can run over UDP (User Datagram Protocol) or TCP, and you can control which paths it uses. At Ludeo, we prefer UDP. Here’s why: TCP is the slow one. The receiver confirms every packet with an “ack”, and anything lost is sent again before the rest can move on. That’s great for loading a web page, but in a game, by the time a lost picture arrives, it’s already too late. UDP doesn’t wait. It just keeps sending, so the game keeps moving.</p><p>UDP is just the foundation, though. On top of it, WebRTC uses four more protocols, each with one job. Think of it as a delivery: DTLS agrees on a secret lock that only the two sides can open, SRTP carries the locked boxes of video and sound, RTCP reports what got lost, and SCTP carries small messages, like your button presses. Each one deserves its own blog post, <a href="https://webrtcforthecurious.com/">so dive deeper if you’re curious</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PRg_DN2_ps9of7a6efg38w.png" /></figure><h3>Part 2: Signaling, Where Every Call Begins</h3><p>Here’s the problem. WebRTC connects two peers directly. At <a href="https://ludeo.com/?utc_source=medium">Ludeo</a>, that’s your browser and the streamer on a gaming machine in the cloud. But before they can connect, they need to share some information. And to share information, they need to be connected. It’s like needing a key to open the box that has the key inside.</p><p>The answer is <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Signaling_and_video_calling">signaling</a>: a small server that works like a broker. It passes messages between the two peers until they agree on a deal, and then it steps aside so they can talk directly.</p><p>The strange part? WebRTC doesn’t care how you do signaling. WebSockets, HTTP, a chat app, a pigeon. Anything is fine, as long as the notes arrive. Most people use WebSockets, which keep a two-way line open between the browser and a server, because pigeons are slow and really hard to debug. If WebSockets are new to you, <a href="https://medium.com/ludeo/beyond-the-handshake-scaling-websockets-with-echo-7d285a78eb6a?sharedUserId=tomerguttman27">this post is a great place to start</a>.</p><h4>Ludeo’s Signaling Proxy</h4><p>At <a href="https://ludeo.com/?utm_source=medium">Ludeo</a>, our broker is called the signaling proxy. Picture a telephone operator from an old movie, sitting in front of a big board full of cables. The operator doesn’t listen to your call. They just plug your cable into the right place and let you talk.</p><p>Here’s its job, step by step:</p><ol><li>Our backend finds a free gaming machine for your game. It sends your browser two things: the address of the signaling proxy, and a list of STUN and TURN servers it will need later.</li><li>Your browser opens a secure WebSocket to the signaling proxy. The address includes the ID of your gaming machine, so the proxy knows exactly where to plug in your cable.</li><li>The proxy passes the notes back and forth between your browser and the streamer on the gaming machine: the offer, the answer and the ICE candidates. (Don’t worry, we’ll explain all three soon.)</li><li>Once the WebRTC connection is ready, the game video and your controls travel directly between the two sides (or through TURN). The proxy’s job is done, and it quietly leaves the call.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n56gD_0WAAk6FH7JAD9vzg.png" /></figure><p>We run a few proxies, so every browser always has a stable “front door”, even though the gaming machines behind it come and go all day. And it’s not just one door. The proxies run in several availability zones (separate data centers in the same area), so if one of them has a bad day, the others keep working. High availability, backups, failover: all those boring words that just mean you keep playing.</p><h4>SDP: The “Here’s What I Can Do” Note</h4><p>The notes are written in <strong>SDP</strong> (Session Description Protocol). An SDP message says what a peer can do: “I can send video, I understand these video formats, and here’s my security info.” Here’s the offer our streamer sends to your browser. The real one is much longer, with way more details about packet recovery, network feedback and security, so I kept only the lines that matter here:</p><pre>v=0<br>o=- 519595617307026549 0 IN IP4 0.0.0.0<br>s=-<br>t=0 0<br>a=group:BUNDLE video0 audio1 application2<br>m=video 9 UDP/TLS/RTP/SAVPF 96<br>a=ice-ufrag:46Tz...<br>a=ice-pwd:rr9b...<br>a=fingerprint:sha-256 78:91:33:54:...<br>a=sendrecv<br>a=rtpmap:96 AV1/90000<br>m=audio 9 UDP/TLS/RTP/SAVPF 111<br>a=sendrecv<br>a=rtpmap:111 OPUS/48000/2<br>m=application 9 UDP/DTLS/SCTP webrtc-datachannel</pre><p>Yes, it&#39;s ugly. It was designed in the 90s, and you can tell. The good news is that you almost never have to read it. The browser writes it and reads it for you.</p><p>Still, a few lines are worth knowing:</p><ul><li><strong>m=video</strong>, <strong>m=audio</strong> and <strong>m=application</strong> are the three parts of our stream: the game picture, the game sound, and the data channel that carries your inputs.</li><li><strong>a=rtpmap</strong> names the format of each part: in this example, AV1 for video (sharp picture, less data) and Opus for audio, at 48 kHz in stereo. The video format can change depending on your browser and device.</li><li><strong>a=group:BUNDLE</strong> puts video, audio and data on one single connection.</li><li><strong>a=ice-ufrag</strong> and <strong>a=ice-pwd</strong> are a short username and password for the ICE checks. <strong>a=fingerprint</strong> is the ID of the security key, so both sides know the encryption is real.</li><li><strong>a=sendrecv</strong> means &quot;traffic can go both ways.&quot; Keep an eye on this one, because the answer changes it.</li></ul><h4>Offer and Answer</h4><p>Alice and Bob are just two WebRTC peers. Each one can be a browser, a phone app, or a server like our streamer. WebRTC doesn’t care. The exchange works a bit like dating:</p><ol><li><strong>Alice makes an offer.</strong> She writes an SDP note that lists everything she can do: video, sound, data, the formats she supports, and her security info. She keeps a copy for herself (her “local description”) and sends the note to Bob through the signaling server.</li><li><strong>Bob gets the offer.</strong> He saves Alice’s note as the “remote description”, so he knows what the other side can do.</li><li><strong>Bob answers.</strong> He compares the offer with what he can do, picks the things they both support, and writes an answer. It basically says: “Cool, let’s use these.” Bob keeps a copy as his own local description and sends it back.</li><li><strong>Alice saves Bob’s answer</strong> as her remote description. Now each side has two notes: its own and the other side’s. Deal done.</li></ol><p>Here are the most important lines from the answer to the offer above (the full answer is much longer):</p><pre>m=video 9 UDP/TLS/RTP/SAVPF 96<br>a=recvonly<br>a=rtpmap:96 AV1/90000<br>m=audio 9 UDP/TLS/RTP/SAVPF 111<br>a=recvonly<br>a=rtpmap:111 OPUS/48000/2<br>m=application 9 UDP/DTLS/SCTP webrtc-datachannel</pre><p>Put it next to the offer and you can see the deal being made:</p><ul><li><strong>Same formats</strong>: the browser says yes to AV1 for video and Opus for audio.</li><li><strong>a=recvonly</strong>: the offer said “sendrecv”, and the browser answers “I’ll only receive.” So the streamer sends the picture and sound, and your browser just watches and listens. Your inputs still go back through the data channel.</li></ul><p>Now both sides agree on <em>what</em> to send. But wait, they still don’t know <em>where</em> to send it. That’s the biggest problem of all, so it gets its own part.</p><h3><strong>Part 3: Finding a Path (</strong><a href="https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Protocols"><strong>NAT, ICE, STUN and TURN</strong></a><strong>)</strong></h3><p>To send data to someone on the internet, you need their address: their IP address. You’d think every computer knows its own address. Plot twist: yours probably has no idea what its public address is.</p><h4>NAT: The Problem</h4><p>At home or at the office, all your devices (your laptop, your phone, even your smart toaster) share one public IP address. The router hides them all behind it. This trick is called <strong>NAT</strong> (Network Address Translation). Your laptop thinks its address is something like 192.168.1.5, but that’s only a private address that works inside the network. Nobody outside can use it.</p><p>It’s like living in a big apartment building. Your friend knows the building’s street address, but not your apartment number. And the doorman doesn’t let strangers in. Very safe. Also very annoying.</p><h4>ICE: The Path Finder</h4><p>ICE (Interactive Connectivity Establishment) is the system that finds a path that works between the two peers. It makes a list of possible addresses, called ICE candidates, and tries them until one works. Each side sends its candidates to the other through the signaling server, one by one, as soon as it finds them. It doesn’t wait for the offer and answer to finish. This is called “trickle ICE”.</p><p>ICE gets its candidates from four places, and each type has a short, slightly weird name:</p><ul><li><strong><em>host</em>:</strong> your device’s own local address, like 192.168.1.5. It usually only works when both sides are on the same network.</li><li><strong>srflx (server reflexive):</strong> your public address, as the outside world sees it. A STUN server tells you what it is (more on that in a moment).</li><li><strong>prflx (peer reflexive):</strong> an address ICE discovers by surprise while testing paths.</li><li><strong>relay:</strong> an address on a TURN server, which passes your data along.</li></ul><p>So how does ICE choose? It gives every candidate a score: <strong>host</strong> scores highest, then <strong>prflx</strong> and <strong>srflx</strong>, and <strong>relay</strong> lowest. Then it tests pairs (one of your candidates plus one of theirs), best score first, and picks the best pair that actually works. It doesn’t measure which path is fastest. It simply prefers direct paths, because they’re usually shorter, faster and free, and keeps relay for last. The prflx candidate is the surprise guest: nobody invited it, but sometimes it’s the one that works.</p><blockquote>A high score doesn’t always mean a good path. We saw this with players on VPNs. A VPN gives the device a second network connection, so ICE collects candidates on both: the normal one and the VPN one. Sometimes ICE picked the path through the VPN. It worked, kind of, but all the game traffic took a detour through the VPN server. Like driving from London to Paris through Tokyo. The fix was to filter out those extra candidates, so ICE picks the normal, direct path. More candidates isn’t always better.</blockquote><p>Still, ICE has two problems it can’t solve alone. First, your device only knows its home address. It has no way to find its public address by itself (remember the doorman?). Second, sometimes there’s no direct path at all, because a strict firewall blocks everything. So ICE calls two helpers: a STUN server, which tells you your public address (that’s your srflx candidate), and a TURN server, which passes your data along when nothing else works (that’s your relay candidate).</p><h4>STUN: The Mirror</h4><p>A <strong>STUN</strong> server answers just one simple question: “What’s my public address?” Your browser asks, and STUN replies: “From out here, you look like 203.0.113.7, port 54321.&quot; Now your browser knows its public address and can share it. STUN servers are cheap to run because they only answer questions. They never carry your video. Often, STUN is all you need to connect.</p><h4>TURN: The Backup Plan</h4><p>Sometimes the network is too strict. Some office firewalls block almost everything, like a doorman who hates fun. When that happens, a direct connection just isn’t possible.</p><p>That’s where <strong>TURN</strong> comes in. A TURN server is a middleman: both sides send their data to it, and it passes the data on. It always works, but it isn’t really peer-to-peer anymore. It adds a bit of delay, and it costs money, because the server has to carry all the video. So TURN is the last option, not the first.</p><ul><li><strong>STUN</strong> tells you your public address. It never carries your video, so it’s cheap: it only answers one tiny question per connection.</li><li><strong>TURN</strong> passes all the data along when the direct path fails. It carries every bit of the game stream, so it’s expensive: cloud providers charge for that traffic, plus you pay for the servers.</li></ul><p>ICE tries the direct paths first and uses TURN only if nothing else works. Smart, lazy and cheap. Just like all good engineers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mtzM9GtZNH57caPcFuBfqw.png" /></figure><h3>Wrapping Up</h3><p>WebRTC peers send video, sound and data straight to each other, in real time. But first, they need a broker. Through signaling, they swap two SDP notes, an offer and an answer, and agree on <em>what</em> to send. Then ICE works out <em>where</em> to send it. It collects possible addresses, asks STUN for the public one, tests the paths, and keeps the best one that works. If a strict network blocks every direct path, TURN steps in as the expensive backup. And the whole time, everything stays encrypted.</p><p>That’s WebRTC, minus the headache. A broker, a few notes, a mirror and one expensive backup plan, all working together so a game running in a data center feels like it’s running on your desk.</p><p>Next time a video call freezes, you’ll know exactly which short name to blame. And next time you play something on Ludeo, you can enjoy the best part: not thinking about any of this at all.</p><p><strong>Want to see it for real?</strong> Go to <a href="https://ludeo.com/?utm_source=medium">ludeo.com</a>, press play, and try it yourself. No plugins, no setup, and no need to think about any of the stuff above.</p><p>And here’s the fun part: you can create your own Ludeo too. <a href="https://play.ludeo.com/l/437629">Here’s one I made</a>. Give it a go and see if you can beat me (<strong>TOMER[‘G]</strong>)!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*x3iaVIbPEkKpZJzV9y21mw.gif" /></figure><p>Liked this post? Follow us here on Medium for more stories from the Ludeo team. And if problems like these sound fun to you, come say hi!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40b4fd2ea834" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ludeo/webrtc-minus-the-headache-40b4fd2ea834">WebRTC, Minus the Headache</a> was originally published in <a href="https://medium.com/ludeo">Ludeo</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond the Handshake: Scaling WebSockets with Echo]]></title>
            <link>https://medium.com/ludeo/beyond-the-handshake-scaling-websockets-with-echo-7d285a78eb6a?source=rss-9a3810d92c03------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d285a78eb6a</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[system-architecture]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ludeo]]></category>
            <dc:creator><![CDATA[Tomer Guttman]]></dc:creator>
            <pubDate>Sun, 17 May 2026 13:53:01 GMT</pubDate>
            <atom:updated>2026-11-12T19:04:30.854Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h-lMswOxO7f5KWOW_UhTnQ.png" /></figure><p><a href="https://business.ludeo.com/">Ludeo</a> is a cloud gaming platform that enable game studios to create short, shareable gaming moments called Ludeos, directly from their games. Studios integrate our SDK once, and from that point on, any player in the game can capture and share their best moments. Think of it like a highlight reel, but interactive: anyone can jump in and play the exact moment a creator shared, from any device, no downloads, no installs, no signups. Just click and play - within seconds. We handle the full streaming infrastructure - studios just ship the SDK, and we take care of the rest.</p><p><strong><em>Real-time isn’t a feature at </em></strong><a href="https://business.ludeo.com/"><strong><em>Ludeo</em></strong></a><strong><em>. It’s the foundation everything is built on.</em></strong></p><p>Echo is the system that keeps that foundation from cracking. It holds long-lived WebSocket connections between clients and our backend, letting data flow both ways like it owns the place - game-events, live updates, and anything else that refuses to wait politely for a refresh button.</p><p>On paper, it sounds simple: “just keep a connection open.” In practice, once you scale past a few clients and servers, things get complicated fast. Suddenly you’re not just “sending messages” - you’re negotiating connection ownership, message routing, delivery guarantees, and the occasional existential crisis at 3AM.</p><p>This post is a look at how we got here, and how we traded “it mostly works” for a system with clear ownership, predictable routing, and a delivery model that doesn’t require prayer as a dependency.</p><h3>The Illusion of Simplicity</h3><p>Most web applications are built around a simple interaction model: the client sends a request, the server responds, and the connection closes. It’s a stateless pattern that scales well for traditional APIs, but starts to break down when applications need to react instantly to changing state.</p><p>Real-time systems have different requirements. Multiplayer sessions, live leaderboards, game-events, collaborative experiences, and streaming updates all depend on the server being able to push data to clients the moment something changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2lzDQNWxtUmEvPB-cIJ2AQ.png" /><figcaption><strong>Company of Heroes running on Ludeo</strong> - every kill, every tank destroyed delivered in real time over WebSocket</figcaption></figure><p>Before WebSockets, applications often relied on polling. Clients repeatedly asked the server for updates at fixed intervals. While simple, polling introduces delivery latency since updates are only discovered on the next polling cycle, and creates significant overhead by repeatedly opening HTTP connections, performing handshakes, transferring headers, and closing requests, even when no new information exists. Individually those operations only take milliseconds, but at scale, across millions of requests, the cost starts to compound quickly.</p><p>WebSockets changed this model by introducing a persistent, bidirectional connection between client and server. Instead of repeatedly reconnecting over HTTP, the client upgrades a single connection and keeps it open, allowing both sides to exchange messages continuously.</p><p>At small scale, this architecture feels straightforward. A client connects, the server keeps the socket open, and events flow naturally between them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*ne8sDUTSmUSHTpu3hpnN8Q.png" /><figcaption><strong>HTTP vs WebSockets:</strong> HTTP creates a new request/response cycle for every interaction, while WebSockets maintain a persistent realtime connection</figcaption></figure><p>The complexity appears once the system stops being a single WebSocket server. WebSocket connections are fundamentally stateful. With traditional HTTP, any request can be routed to any backend instance. With WebSockets, each live connection remains attached to the specific server that accepted it.</p><p>That distinction changes how systems behave during scaling events, deployments, and failures. In a stateless API, instances can usually be added or removed transparently behind a load balancer. Existing requests complete, new requests shift elsewhere, and the system continues operating with minimal coordination.</p><p>Persistent connections make this significantly more complex. Removing a node now means dealing with thousands of active clients connected to it. Scaling events introduce connection rebalancing concerns, graceful shutdown becomes a coordinated drain process rather than simply terminating a process, and failures require clients to reconnect and re-establish state against a different server.</p><p>Once connection ownership becomes part of the system itself, coordination starts to matter just as much as transport.</p><h3>Everyone Gets the Message</h3><p>Before Echo, the real-time system evolved in a fast-paced startup environment, with architecture decisions constantly optimized for speed of delivery. The initial setup used a managed WebSocket provider to move fast, and over time it was replaced with an in-house WebSocket infrastructure as realtime became core to the product.</p><p>At that point, WebSocket servers were already consumers of our Kafka event streams, each maintaining its own local map of connected clients. When an event arrived, a server would first check whether it held the target socket locally. If it did, it would deliver the message directly. If not, it would fall back to publishing the event through Redis pub/sub, effectively broadcasting it across the cluster so that every other WebSocket server could check its own local state and attempt delivery.</p><p>So routing wasn’t really centralized, it was a simple two-step flow: try locally, otherwise flood the cluster and let every WS server figure it out.</p><p>It worked, but as traffic grew, that approach started to show its limits in both cost and predictability. Every message effectively hit the entire system before finding its target.</p><blockquote>Consider a cluster with 10 servers. Each message can be sent to all 10 consumers, but only one actually has the target socket. That gives just a 10% chance of hitting the correct server on the first attempt. When it misses - which happens 90% of the time - the message falls back to the Redis pub/sub system, broadcasting across the entire cluster so each server can check its local state and try delivery. Every failed delivery becomes a cluster-wide event. As you add more servers to handle the load, the probability of hitting the right server on the first attempt doesn’t remain at 10% - it drops toward zero, while the cost of each miss keeps increasing.</blockquote><p>The deeper issue wasn’t just inefficiency, it was loss of determinism. As the system scaled, it became harder to understand where an event would end up, how many times it would be processed, or what path it took through the system. Delivery became something the system <em>happened</em> to achieve through cluster-wide distribution, rather than something it was directly designed for. That made debugging <strong>harder</strong>, scaling more <strong>expensive</strong>, and changes <strong>riskier</strong>, because no single component had a full picture of message flow.</p><p>These gaps in ownership weren’t isolated to routing alone. They showed up across the system in a few recurring patterns:</p><ol><li><strong>Fan-out to every pod</strong> - Without a registry of socket ownership, messages were broadcast across all WebSocket servers, even though only one actually held the connection</li><li><strong>Centralized delivery bottleneck</strong> - Our WebSocket servers consumed a large number of Kafka topics and handled delivery directly, so every new topic meant modifying and redeploying the servers. As topic counts grew, consumer group rebalances became increasingly slow and disruptive</li><li><strong>No consistent connection lifecycle</strong> - Connection handling wasn’t standardized (ping/pong, reconnection, jitter, graceful shutdown), leading to inconsistent recovery behavior across servers and clients</li><li><strong>Business logic inside WebSocket servers</strong> - Routing, deserialization, and subscriptions lived in the transport layer, increasing coupling and limiting scalability, <strong>driving throughput down and latency up</strong></li><li><strong>No shared model</strong> - Different WebSocket implementations evolved independently with inconsistent protocols and message formats</li><li><strong>Limited observability and testing</strong> - Issues surfaced, with gaps in logging, metrics, and end-to-end validation</li></ol><p>Taken together, these weren’t isolated issues - they all pointed to the same problem: there was no clear model of ownership or routing for realtime behavior, and every part of the system was making its own assumptions.</p><p>At that point, it was clear that fixing individual components wouldn’t be enough. We needed to step back and redefine the flow itself: what owns a connection, how events are routed, and how delivery becomes predictable end-to-end.</p><h3>The Guessing Game Stops Here</h3><p>Echo is our answer to the chaos. Instead of flooding the cluster and hoping the right server picks up the message, Echo introduces a simple guarantee: <strong><em>Every socket lives on a known server, and every event is delivered directly to it. No broadcasting, no fallbacks, no 10% hit rates. Just a single, deterministic path that does exactly what you tell it to</em></strong>.</p><p>Under the hood, Echo is split into two flows: <strong>Intake</strong> and <strong>Broadcast</strong>.</p><p><strong>Intake</strong> handles everything coming from clients - from registering new connections to forwarding client messages into our backend services through Kafka. <strong>Broadcast</strong> is the reverse path: it takes events produced by our backend services, resolves each one to the exact server that owns the target socket, and delivers it directly.</p><p>This separation is what makes routing deterministic: we always know where a connection lives, and we always know how messages flow in both directions.</p><p>At a high level, <strong>Intake</strong> and <strong>Broadcast</strong> form a continuous loop around Kafka. When a client connects, Echo registers the socket and binds it to a specific server. From that point on, client messages are published into Kafka as events, fully decoupled from downstream services.</p><p>Backend services do their thing - firing events into Kafka, completely unaware of which server holds the socket. The Broadcast flow handles the detective work: it checks the registry, finds the right server, and delivers the message straight to its destination.</p><p><strong><em>Don’t worry - we’ll dive into the architecture shortly.</em></strong></p><h3>The Backbone: Kafka, and Aerospike</h3><p>If Echo is the nervous system, Kafka and Aerospike are the spine. We chose them because real-time systems at scale have no room for weak links - connection ownership and message delivery have to be fast, and rock solid, every single time.</p><h4>Kafka: The Reliable Transport</h4><p>Every message flowing through Echo - whether it’s a game-state update or a UI notification, passes through Kafka. It’s more than just a pipe; it’s our insurance policy:</p><ul><li><strong>High Availability &amp; Replication:</strong> High replication factor, in-sync replicas - if a broker goes down, the event streams don’t even blink. That’s not luck, that’s the kind of redundancy that makes on-call rotations a lot less terrifying</li><li><strong>Decouple everything, lose nothing:</strong> Kafka sits at the center of both Intake and Broadcast, cleanly separating transport from business logic. Need to scale? Add more consumers. Need to catch up on missed events? The data is sitting right there, waiting patiently. No drama, no data loss</li><li><strong>Order Guarantees:</strong> Partitioning by socket_id means each player gets their own dedicated lane in Kafka. In our SDK play/record flows, messages arrive exactly in the order they were sent - because in real-time gaming, order matters</li></ul><h4>Aerospike: The Registry</h4><p>When an event hits the system, we have microseconds to decide where it goes. We use Aerospike as our global socket registry because it offers:</p><ul><li><strong>Predictable Sub-Millisecond Latency:</strong> Its hybrid-memory architecture ensures that lookup times stay flat, even if we’ll scale to millions of concurrent connections</li><li><strong>Global Resilience via XDR:</strong> Aerospike’s <strong>Cross-Datacenter Replication (XDR)</strong> is what allows Echo to go global. It synchronizes socket metadata across regions automatically. If a player is playing in eu-central-1, but a backend service in us-east-1 needs to send them a message, XDR ensures the US cluster “knows” exactly where that player is sitting without a slow cross-ocean API call</li><li><strong>Secondary Indexes &amp; Lua UDFs:</strong> This is how we solve the “zombie connection” problem. If a Kubernetes node disappears, we use secondary indexes on server_addr to find and purge stale registrations in one call</li></ul><h3>The Architecture</h3><p>Echo is built as a small set of tightly scoped microservices that implement the two core directions of realtime communication: moving messages <strong>from clients into backend services</strong>, and delivering events <strong>from backend services back to clients</strong>. Internally, we refer to these flows as <strong>Intake</strong> and <strong>Broadcast</strong>. Each service owns a single responsibility within that pipeline, forming a deterministic path from WebSocket connection to backend processing and back again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*02SXmOweIY8iI1n3_DyIDQ.jpeg" /><figcaption>Echo architecture overview - deterministic WebSocket routing for scalable realtime event delivery</figcaption></figure><p>At a high level, the system is built around four core microservices and a shared npm package:</p><ul><li><strong>Echo-Server:</strong> The entry point for all WebSocket connections. It handles connection lifecycle management - establishing sockets, maintaining heartbeats, and routing all inbound client messages into the Intake flow after careful validation. It also exposes an internal API used by Echo-Worker to forward events to connected clients</li><li><strong>Echo-Manager:</strong> The source of truth for connection ownership. It tracks which server each socket is attached to and provides fast lookups used for routing during Broadcast. It also handles user authentication at the time of WebSocket registration, ensuring only valid connections recorded in the system</li><li><strong>Echo-Router: </strong>The ingestion layer that consumes client events from the Gateway (Echo-Server), normalizes them, and publishes them into Kafka for downstream services. It ensures client traffic is fully decoupled from backend processing</li><li><strong>Echo-Worker:</strong> This is how backend events are delivered to our clients. It consumes events from Kafka, resolves the target connection via Echo-Manager, and delivers straight to the Echo server that owns it</li><li><strong>@ludeo/echo</strong>: The part our developers actually interact with. It’s a lightweight npm package that abstracts away connection setup, serialization, and reconnection logic - exposing a clean, simple interface for publishing and receiving events. The Echo components handle moving the messages; this package ensures schema definitions, constraints, and internal contracts stay consistent without developers having to think about how it all works under the hood</li></ul><p>Together, these components turn realtime delivery into a predictable pipeline: clients connect through Echo, messages flow through Kafka, and events are delivered directly to the server that owns the target connection, and back again.</p><h3>Deep Dive: Intake and Broadcast</h3><p>Both flows orbit the same idea: a single message, taking a deterministic path. The cleanest way to describe them is to follow one message at a time.</p><h4>Intake: The client speaks</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dx_RLaU6ukPQsc75ULpkxg.png" /></figure><p>A client opens a connection using <strong>@ludeo/echo</strong>, our in-house client library. The library handles the connection lifecycle, query parameters, and exponential backoff on failure. From the client’s perspective, “connecting” is a single Promise; from Echo’s perspective, a lot has already happened.</p><p>When the upgrade request reaches Echo-Server, it’s handled manually rather than being delegated to the WebSocket library. Echo-Server first validates the path and query parameters using a strict Zod schema, and only then registers the socket in Echo-Manager - before the WebSocket handshake is completed. That ordering is deliberate. It allows token validation and registration to happen in a single step, ensuring a mapping to the exact pod is written to Aerospike before the client even sees a successful upgrade. If anything fails between registration and handshake completion, the registration is rolled back. No orphaned connections on the way in.</p><p>Once connected, every incoming client message is wrapped into a Kafka record with structured headers - socket_id, correlation_id, socket_type, client_type - and published to the intake topic. One detail worth mentioning: for SDK clients, the Kafka partition key is the socket ID, ensuring per-socket ordering. Messages from the same player consistently land in the same partition and preserve order. UI-oriented clients, on the other hand, don’t set a key and are distributed round-robin across partitions. Two ordering models, a single producer path.</p><p>That socket_id header isn’t decoration. It’s the breadcrumb that ties an inbound event back to the exact connection it came from. Downstream backend services don’t have to guess “who said this?” - the answer is right there in the Kafka headers. And when those services later want to reply, they have everything they need to address the response back to the same socket: drop socket_id into the broadcast envelope’s data.context, and Echo-Worker takes it from there. Same identity, full round trip.</p><p>Echo-Router consumes from the intake topic and branches based on socket_type. This separation is intentional - by moving message deserialization and validation out of Echo-Server and into Echo-Router, the gateway is freed from the cost of opening every message. Echo-Server stays lean, focused purely on connection handling, while Echo-Router does the heavy lifting: decoding, validating, and routing. The result is higher throughput and lower latency at the gateway layer, because the two concerns never compete for the same resources.</p><p>SDK binary messages are decoded using FlatBuffers, with a few necessary safeguards like splitting oversized state payloads across multiple Kafka messages to stay within Kafka broker limits. UI text messages are parsed as JSON and validated with Zod. In both cases, Echo-Router ensures socket_id is present, adding it if the client didn&#39;t provide it, so routing identity exists in both the Kafka headers and the message body.</p><p>From there, normalized events are published to the appropriate downstream topic.</p><h4>Broadcast: The backend speaks</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xrzMu9MZWr8G2GZwqbgB1w.png" /></figure><p>The reverse path begins with a backend service using <strong>@ludeo/echo</strong> to publish a JSON envelope to our Kafka broadcast topic. The envelope structure is identical to what a WebSocket client would send - both sides use the same envelope, so clients and backend services share an identical wire format.</p><pre>export type Envelope = {<br>  v: string;                                                     // Envelope version - lets us evolve the format without breaking consumers<br>  type: string;                                                  // Discriminator for the receive handler<br>  id: string;                                                    // UUID, unique per envelope - useful for dedup/tracing<br>  ts: number;                                                    // Epoch millis at construction time - powers RTT measurements (e.g. ping/pong) and latency histograms<br>  data: {<br>    context: {<br>      topic?: string;                                            // Intake-only - the Kafka topic Echo-Router should publish to. Irrelevant on the broadcast path<br>      event_name: string;                                        // Logical event name (e.g. &quot;match.score.updated&quot;) - how downstream consumers discriminate<br>      event_id: string;                                          // UUID for this specific event instance<br>      correlation_id: string;                                    // Trace id - propagated to Kafka headers and the HTTP X-Ludeo-Request-Id; lets us follow one logical request end-to-end across services<br>      socket_id: string;                                         // The connection this message is from (intake) or to (broadcast). Stamped by Echo-Server on intake; Set by producer on broadcast to target the socket by ID<br>      origin: string;                                            // Producer identity - which service emitted this. Mostly relevant on broadcast (e.g. &quot;match-service&quot;, &quot;leaderboard-service&quot;)<br>      [key: string]: string | number | boolean | undefined;      // Escape hatch for app-specific routing/trace fields - typed loosely to keep the envelope generic<br>    };<br>    payload: any;                                                // Application-defined content<br>  };<br>};</pre><p>Echo-Worker consumes the broadcast topic. For simplicity, we’ll focus on the most direct case: a message targeted at a specific socket via data.context.socket_id - one connection, one delivery.</p><p>Echo-Worker queries Echo-Manager to retrieve the registration, performed as a single primary-key lookup in Aerospike - typically completing in sub-millisecond to a couple of milliseconds in-region. The result is a record containing the critical server_addr - the <strong><em>IP and port</em></strong> of the exact pod that owns the connection.</p><p>Then comes the part that makes routing deterministic in practice: Echo-Worker sends a direct call to the target pod at http://{server_addr}/websockets/{id}/send. No service mesh, no load balancer, no broadcast layer - just a point-to-point call into the exact Echo-Server that owns the socket. <strong><em>Echo also handles fan-out, where a single event needs to reach multiple clients at once. We’ll save that one for its own post - it deserves the space.</em></strong></p><h3>The Server Layer: Lifecycle, Shutdown, and Reality</h3><p>Echo-Server sits at the entry point of the system, managing thousands of long-lived connections simultaneously. It’s the layer where every detail of the WebSocket protocol matters, every edge case surfaces, and every shortcut eventually turns into a 3AM incident.</p><p><em>The design is driven by four core ideas: owning the lifecycle, dual-layer heartbeats, intentional reconnect cycles, and graceful shutdown as a coordinated process.</em></p><h4>We didn’t want a black box</h4><p>Echo-Server uses the <a href="https://github.com/websockets/ws">ws</a> library with three deliberate “we own this” toggles:</p><pre>import { IncomingMessage, Server } from &#39;http&#39;;<br>import { ..., WebSocketServer } from &#39;ws&#39;;<br><br>class WsServer {<br>  ...<br><br>  constructor(server: Server, ...) {<br>    this.wsServer = new WebSocketServer({<br>      autoPong: false,                // We handle pong manually to preserve RTT measurement and metadata.modified updates<br>      noServer: true,                 // We intercept HTTP upgrades ourselves to register sockets in Echo-Manager before the handshake completes<br>      maxPayload: env.WS_MAX_PAYLOAD, // Hard cap on frame size to prevent memory blowups from malicious or misbehaving clients<br>      clientTracking: false,          // We maintain our own socket registry, avoiding duplicate state and a second source of truth<br>      ...<br>    });<br>  <br>    ...<br><br>    server.on(&#39;upgrade&#39;, ...);        // We handle WebSocket upgrades manually<br><br>    ...<br>  }<br>}</pre><p>noServer: true means we handle the HTTP upgrade ourselves, which allows us to register the socket in Echo-Manager before the handshake completes. autoPong: false disables silent automatic ping responses, because we rely on those frames to measure RTT and update the modified marker that drives the heartbeat loop. clientTracking: false means we maintain our own socketId-to-WebSocket mapping, which is exactly what Echo-Worker queries during HTTP delivery.</p><p>The library handles the protocol; we handle the lifecycle. Each of these flags is a small “we take control” decision - and together, they’re what make the rest of this system possible.</p><h4>Two ping/pong stories, by design</h4><p>Echo-Server runs a heartbeat loop that periodically pings every active socket with a timestamp payload. When the client responds with a pong, we measure RTT, refresh the modified marker, and continue. This is the native WebSocket control-frame channel - efficient, protocol-level, <strong>and invisible to JavaScript in the browser.</strong></p><p>That invisibility is the tradeoff: the server can observe liveness, <strong>but in browsers</strong> <strong>the native ping/pong protocol is handled at the WebSocket layer, below anything the client can access</strong>. The client can’t see those frames, measure RTT, or reliably detect when a connection has gone stale. So we introduce a second ping/pong flow over the data channel: a JSON {&quot;type&quot;:&quot;ping&quot;...} message that the <strong>@ludeo/echo</strong> client can explicitly handle. Same idea, different layer - this gives us visible, application-level liveness and reconnect logic on the client side.</p><p>On top of that, the same heartbeat loop enforces a maximum connection lifetime. Once a socket crosses a configured threshold, Echo-Server closes it with code 1001 and lets the client reconnect. This introduces intentional connection resets, preventing long-lived sockets from silently drifting out of sync over time. It also gives us a natural way to redistribute WebSocket load across servers, improving balance as the system scales.</p><h4>Shutdown is a choreography, not a kill -9</h4><p>When Kubernetes sends a SIGTERM. The naive response is: the process exits, sockets drop, and clients reconnect. In practice, clients don’t notice immediately - there’s a short delay before they detect the disconnect, and then they all reconnect at once. That spike lands directly on the other pods, which takes the hit. So Echo-Server treats shutdown as its own protocol.</p><pre>on SIGTERM:<br><br>  wait SERVER_SHUTDOWN_DELAY              // Let k8s LB stop routing traffic to us<br>  server.close()                          // Stop accepting new HTTP requests<br>  ws.close()                              // Refuse new WS upgrades<br><br>  sockets = snapshot(active_sockets)      // Freeze current connection state<br>  batch_size = floor(<br>    len(sockets) *<br>    SHUTDOWN_BATCH_SIZE_PERCENTAGE<br>  )                                       // Scale batch size with load<br><br>  for batch in chunks(sockets, batch_size):<br>    for s in batch:<br>      s.close(1001, &quot;Going Away&quot;)         // Signal client to reconnect<br><br>     wait CLOSE_BATCH_DELAY_MS            // Avoid thundering-herd reconnect<br><br>  deadline = now() + FORCE_TERMINATE_MS   // Max time allowed for graceful shutdown<br><br>  while active_sockets and now() &lt; deadline:<br>    wait 1s                               // Give in-flight closes time to settle<br><br>  for s in active_sockets:                // Anyone still hanging on...<br>    s.terminate()                         // ...Gets forcefully disconnected<br><br>  cleanup(server_addr)                    // Evict leftover registry state in Echo-Manager<br>  exit(0)</pre><p>The 1001 close code is the same “please reconnect” signal we use when a connection reaches its lifetime limit, so client behavior stays consistent whether we’re scaling down or rotating long-lived sockets. (What the client does with that signal is the next beat.)</p><p>And when the choreography fails - because reality, again - we fall back to a safety net. Pods don’t always get the chance to shut down gracefully: OOMs, kernel panics, or hard kills happen. When they do, the shutdown flow never runs, and Echo-Manager (backed by Aerospike) can be left with stale registrations pointing at dead servers.</p><p>To handle this, a periodic cleanup job calls a cleanup endpoint that triggers a reconciliation flow: Echo-Manager reads all stored server mappings from Aerospike, compares them with the live set of Echo-Server pods from Kubernetes <a href="https://kubernetes.io/docs/concepts/services-networking/endpoint-slices/">EndpointSlices</a>, and removes anything that no longer exists.</p><p>One endpoint, two flows - graceful shutdown for the happy path, and periodic reconciliation for everything else. Either way, stale state doesn’t linger.</p><h4>The client side: Built for the real world</h4><p>Server-side resilience is only half the story. Connections drop, networks stutter, laptops sleep, and browser tabs get aggressively throttled. The <strong>@ludeo/echo</strong> package is built with that reality in mind.</p><p>Auto-retry is enabled by default. Any unexpected close triggers a reconnect loop with exponential backoff plus ±20% jitter, so clients dropped by the same event don’t all reconnect at once and overload the system. There’s no max-attempt limit - the loop continues until it reconnects, the client explicitly disconnects, or it receives a non-retriable “close” code like 1000 (clean close) or 1003 (unsupported data).</p><p>The result is the difference between a temporary network blip being invisible, and the same blip turning into a support ticket.</p><p>We also handle browser tab throttling by design. Background tabs can delay or pause activity in ways that would normally break naive connection assumptions. The package is built so that players on Ludeo can switch tabs freely without random disconnections or false “disconnected” states.</p><p>The combination - unsynchronized retries, tab-throttling resilience, and explicit server-driven reconnect signals - means Echo stays reliable in exactly the situations where most WebSocket systems quietly fall short.</p><h3>It was worth it!</h3><p>The old system came with its share of bottlenecks, reconnect storms, fan-out floods, and operational headaches. All of those issues are now gone.</p><ul><li><strong>RESTful by design</strong> - Every internal API across Echo is RESTful, part of a broader shift toward becoming API-first. Clean contracts, predictable interfaces, no tribal knowledge required to integrate</li><li><strong>Routing</strong> went from a cluster-wide pub/sub flood to deterministic per-socket delivery - a registry that knows exactly which pod owns each connection, no guessing, no broadcasting to everyone and hoping for the best</li><li><strong>State</strong> stopped living in every WebSocket server’s own little map and moved into a single Aerospike-backed registry with fast secondary index lookups and a Lua UDF powering the global cleanup path. One source of truth, everywhere</li><li><strong>Topics</strong> used to mean redeploying our WS servers every time a new event entered the picture. Now Echo-Workers simply listen to the broadcast topic - one topic, multiple partitions. New event flows in, a worker picks it up, no redeploy, no drama</li><li><strong>Lifecycle</strong> - It was chaos of inconsistent ping/pong, reconnect, and shutdown behavior scattered across services. Now it’s one set of conventions: heartbeats and batched shutdown baked into Echo-Server, backoff with jitter and inactivity-driven pings baked into <strong>@ludeo/echo</strong></li><li><strong>One package for everything</strong> - Backend services and frontend clients both use <strong>@ludeo/echo</strong>. The Kafka producer and the WS client share the same envelope, so the wire format is identical in both directions</li><li><strong>Observability that actually tells a story</strong> - Every service ships Prometheus metrics: RTT histograms, per-message latency, connection duration, message sizes, even a shutdown-duration histogram on Echo-Server. End-to-end timings instead of “something is slow, somewhere”</li><li><strong>Alerts that fire on the right things</strong> - Kafka consumer lag, processing-time SLOs, error-rate budgets, non-responsive terminations, shutdown overruns, error-logs. If something is drifting, we know before our customers do</li><li><strong>Multi-AZ for HA</strong> - Every Echo component runs across multiple availability zones. A zone going down is a non-event: sockets reconnect, Aerospike keeps serving, Kafka consumers rebalance. The system is designed to survive</li></ul><p><strong>Echo</strong> replaced a fragile WebSocket layer with something designed to scale from the ground up - <strong><em>and every component scales on its own terms</em></strong>. No single bottleneck, no forced coupling. Routing is deterministic, state lives in one place, and the connection lifecycle is consistent across every service. New event types flow in without a redeploy, and a single shared package means backends and frontends speak the same language on the wire.</p><p>The system is observable end-to-end, not just “something is slow, somewhere” - and alerts fire on things that actually matter before customers notice. Multi-AZ deployment means a zone going down is an inconvenience for the infrastructure, not an incident for the team.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-pG09zdlM-RIezujHuWOeA.png" /><figcaption>Consumer lag on Echo-Worker and Echo-Router fires P1 alerts automatically - <strong>Strimzi</strong> Kafka operator metrics do the watching so we don’t have to</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xs9gKX3JinW4OkrdAuOQng.png" /><figcaption>A glimpse into Echo-Server’s <strong>staging</strong> dashboard. We have dashboards for everything. If it moves, we measure it</figcaption></figure><p>Is it perfect? Not yet. The foundation is strong, the gaps are known, and the next improvements have a clean surface to build on.</p><h3>Foundation, Not a Finish Line</h3><p>The biggest win isn’t a benchmark. It’s that routing is no longer something that happens to us - it’s something we control. We can take any message, trace its path end-to-end, and understand exactly why it ended up where it did. That level of visibility turns debugging from archaeology into reasoning, scaling from guesswork into engineering, and 3AM incidents into short, predictable fixes.</p><p>None of the ideas in Echo are novel. Exponential backoff, partition keys, batched shutdown, registry-based routing, and more are all well-worn techniques. The work was in composing them into a system with a single, concrete constraint: a delivery model that doesn’t require prayer as a dependency.</p><p>The real shift is deterministic ownership. “Who owns this socket?” used to be a philosophical question - now it’s a primary key lookup. That change is what makes everything else possible. As for what’s next - a few teasers, no commitments. And honestly? There’s so much more we can do.</p><p><strong>Fan-out</strong> is already part of Echo, but the full story - one event, many sockets, delivered correctly and efficiently at scale, deserves its own post. <strong>Multi-region socket affinity</strong>, so each socket lands on a server closest to the backend services most likely to talk to it, keeping delivery local and skipping the expensive cross-region round trip. <strong>Connection-aware load balancing</strong>, so new sockets always go to the least-loaded Echo-Server, no more blind round-robin. <strong>Dedicated dashboards that make the system accessible to everyone</strong>, not just engineers with Postman - pull up a socket, trace a delivery, answer your own question. Observability shouldn’t require a PhD in RESTful APIs.</p><p>And finally, none of this would exist without the people who built it. A huge thank you to <a href="https://www.linkedin.com/in/omer-sher-0a828971/">Omer Sher</a>, <a href="https://www.linkedin.com/in/eden-feller-14b8a717b/">Eden Feller</a>, <a href="https://www.linkedin.com/in/niv-raviv/">Niv Raviv</a>, <a href="https://www.linkedin.com/in/shai-moria-607933100/">Shai Moria</a>, and <strong>Claude -</strong> for the hard work and late nights. This one’s yours too.</p><p>If you have any questions, feel free to reach out or drop them in the comments. <a href="https://www.linkedin.com/company/ludeoofficial/jobs/"><strong><em>We’re also hiring backend engineers</em></strong></a><strong><em> - and this is just the tip of the iceberg. If building systems like this sounds interesting to you, we’d be happy to talk</em></strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d285a78eb6a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ludeo/beyond-the-handshake-scaling-websockets-with-echo-7d285a78eb6a">Beyond the Handshake: Scaling WebSockets with Echo</a> was originally published in <a href="https://medium.com/ludeo">Ludeo</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Trace Me If You Can: Our Opentelemetry Journey]]></title>
            <link>https://medium.com/payu-engineering/trace-me-if-you-can-our-opentelemetry-journey-294d9775b2d0?source=rss-9a3810d92c03------2</link>
            <guid isPermaLink="false">https://medium.com/p/294d9775b2d0</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[opentelemetry]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[tracing]]></category>
            <dc:creator><![CDATA[Tomer Guttman]]></dc:creator>
            <pubDate>Mon, 07 Jul 2025 09:31:45 GMT</pubDate>
            <atom:updated>2025-07-09T07:33:15.382Z</atom:updated>
            <content:encoded><![CDATA[<h4>A deep dive into how we rolled out OpenTelemetry tracing in hundreds of Kubernetes microservices, running across multiple clusters — all without changing a single line of code</h4><p><em>Ever built a feature, sent a request, and watched it vanish into a maze of microservices, and what felt like a black hole, only to be greeted by an error? So you open the logs, and realize you have no idea where the request even went, let alone where it exactly broke.</em></p><p><em>Yeah. We had that feeling too.</em></p><p><em>In modern distributed systems, figuring out where things go wrong can feel like detective work, but with fewer clues and more timeouts. Sometimes, you’re not even sure which services the request actually went through, so you open up five log windows, grep your way through UUIDs, and try to reconstruct the crime scene like a backend Sherlock Holmes.</em></p><p><em>Logs help. If you know where to look. Metrics tell you something’s off, but not always what. Tracing? Tracing is the GPS of your backend. And </em><strong><em>OpenTelemetry</em></strong><em> is your all-in-one tracker.</em></p><p><em>In this post, we’ll break down how to get started with OpenTelemetry tracing using the OTel Operator, decode the buzzwords along the way, and show how tracing helps you piece together the full story — fast.</em></p><p><em>Let’s follow some traces and see what really happens behind the scenes. Spoiler: It’s more complicated than you think.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lyp3SnnoBHNezIGTzVQqxg.png" /></figure><h3>Buzzwords, Buzzwords Everywhere</h3><p>Before we dive deeper, let’s unpack some of the tracing jargon so we’re all on the same page.</p><p><strong>Span</strong><br>A single operation inside a trace — think of it as one stop or hop on a request’s journey through your system.</p><p><strong>Trace</strong><br>A collection of spans that together tell the full story of a request’s path across services.</p><p><strong>Trace ID</strong><br>The secret sauce that keeps all spans linked as the request bounces between services. Without it, each service would log traces like lost orphans with no connection.</p><p><strong>Instrumentation</strong><br>Code — either written or added automatically using auto-instrumentation — that creates spans and attaches context like the Trace ID. Imagine planting GPS trackers on your microservices to follow their every move.</p><p><strong>OpenTelemetry Collector</strong><br>Think of this as the air traffic controller for telemetry data. It receives spans from our applications, processes them, and sends them onward to wherever they need to go</p><p><strong>Sampling</strong><br>Tracing every single request gives you lots of data — but it’s expensive and overwhelming. Sampling helps by choosing which traces to keep.</p><ul><li><em>Head-sampling</em> — In head-based sampling, the decision to keep or drop a trace is made right at the start, typically when the first span is emitted. Since the full trace hasn’t been assembled yet, the decision relies on limited context — usually just that initial span. If the sampling criteria aren’t carefully tuned, this can lead to lost traces</li><li><em>Tail-sampling —</em> Waits until the full trace is constructed before making a decision, so we can pick only the slow or error-filled traces, etc. This is smarter but requires extra coordination and buffering</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*NkqCm0e_wSD5MLtqAOMTAQ.png" /><figcaption>Head-based vs. Tail-based sampling</figcaption></figure><p><em>We use both</em>: quick head sampling at the edges, and more thoughtful tail sampling in our main cluster to focus on what really matters.</p><p>Now that we’ve unpacked some key terms, you can think of distributed tracing as a GPS system for your requests. Spans are the stops along the way, trace IDs keep everything connected, and sampling helps us avoid drowning in data. <strong>OpenTelemetry</strong> is the Swiss army knife that ties all these pieces together, making it easier to see exactly where your system might be slowing down or breaking.</p><p>With these basics under our belt, let’s dive into why we decided to bring tracing into our own stack.</p><h3>The Missing Tool in Our Debugging Arsenal</h3><p>Imagine trying to solve a mystery without knowing which rooms the suspect visited — that was us before tracing. Our logging stack (FluentBit, Kafka, Fluentd, Coralogix) gave us great context, but stitching together a request’s journey across microservices often felt like flipping through a thousand-page novel to find a single typo.</p><p>When every second counts — slowdowns, errors, weird behavior — we’d grep UUIDs, open dashboards, and piece together clues like backend Sherlock Holmes. Logs and metrics are helpful, but they rarely tell the whole story. We didn’t just want hints — we wanted the full crime scene, with the trail clearly mapped. That’s where tracing came in.</p><p>Tracing promised us:</p><ul><li><strong>Visibility across services:</strong> Follow a request as it travels, no matter how many handoffs it passes through</li><li><strong>Faster debugging:</strong> Instead of chasing random log and UUIDs, we’d get a visual path highlighting bottlenecks and errors</li><li><strong>Performance insights:</strong> Spot slow operations and understand if the problem is in the database, the network, or somewhere else</li></ul><p>Incorporating tracing into <a href="https://coralogix.com/?qgad=749795357514&amp;qgterm=coralogix&amp;_bt=749795357514&amp;_bk=coralogix&amp;_bm=e&amp;_bn=g&amp;_bg=176166699022&amp;gad_source=1&amp;gad_campaignid=22506862741&amp;gbraid=0AAAAAobtWqU44-M4dkgjCBWRNV8acnCj_&amp;gclid=Cj0KCQjw1JjDBhDjARIsABlM2Ssqg5U-pL76bOtip3qUfkHrv1w5dGX8k5CMWf8USu6I77x3B-hkI4IaAqbBEALw_wcB">Coralogix</a> opened up a whole new world for us. Suddenly, we had richer alerts, clearer SLO tracking, and the ability to <strong>correlate</strong> logs and traces seamlessly using trace IDs, helping us get the full picture faster than ever before.</p><p>Ever wondered what your system looks like as a whole? With tracing and service maps, we gained clear visibility into how our services interact, pinpointed the real bottlenecks, and identified each service’s main dependencies and consumers. This means that when an error occurs, we can quickly understand which services might be impacted and respond faster.</p><h3>First Steps Towards Tracing at Scale (POC)</h3><p>While exploring ways to bring tracing into our system, we came across the <a href="https://opentelemetry.io/docs/platforms/kubernetes/operator/">OpenTelemetry Kubernetes Operator</a>. Traditionally, adding tracing meant diving into each codebase or pulling in OpenTelemetry libraries for auto-instrumentation. But with hundreds of microservices, making manual changes to every single repo just wasn’t realistic. <strong><em>Our goal with this POC was to see if this Operator could give us tracing with minimal friction — and ideally, without touching a single line of our applications code</em></strong>.</p><p>To bring tracing to life in our clusters, we used the <strong>OpenTelemetry Kubernetes Operator</strong> to roll out auto-instrumentation at scale — enabling tracing across services without touching application code. Here’s how the pieces come together.</p><ol><li><strong><em>OTel Operator</em></strong> — The Operator manages OpenTelemetry CRDs in our cluster — Collectors, Instrumentation, and more. It watches for custom resources and handles deployment and configuration automatically, saving us a ton of manual work. It also uses Kubernetes webhooks (validating and mutating) to check pod configurations and inject the necessary environment variables and init-containers into our pods—making instrumentation possible without touching a single line of applications code. With hundreds of microservices, this was a game-changer for us</li><li><strong><em>Instrumentation CRD </em></strong>— This is where auto-instrumentation happens. The Instrumentation CRD tells the Operator how to inject OpenTelemetry SDKs into our workloads, no code changes needed</li><li><strong><em>OTel Collector</em></strong> — The Collector acts as the trace router. It receives spans from our apps, processes them (batching, enriching, filtering, etc.), and can send the spans to another collector for further processing or directly to our backend (<a href="https://coralogix.com/?qgad=749795357514&amp;qgterm=coralogix&amp;_bt=749795357514&amp;_bk=coralogix&amp;_bm=e&amp;_bn=g&amp;_bg=176166699022&amp;gad_source=1&amp;gad_campaignid=22506862741&amp;gbraid=0AAAAAobtWqU44-M4dkgjCBWRNV8acnCj_&amp;gclid=Cj0KCQjw1JjDBhDjARIsABlM2Ssqg5U-pL76bOtip3qUfkHrv1w5dGX8k5CMWf8USu6I77x3B-hkI4IaAqbBEALw_wcB">Coralogix</a>)</li></ol><blockquote>💡 <strong><em>However, we made one deliberate choice</em></strong><em>: instead of relying on the </em><em>OpentelemetryCollector CRD, we chose to manage the Collector’s deployments ourselves without the CRD. This gave us </em><strong><em>full control</em></strong><em> over rollout strategies, configurations, and lifecycle management—especially important as we tuned performance and scaling behavior across environments. The Operator still manages other OpenTelemetry components like the Instrumentation CRD and handles the injection of init-containers into pods via its mutating webhook, </em><strong><em>but we wanted to retain full control over the collectors themselves</em></strong><em>.</em></blockquote><p>We started by installing the OpenTelemetry CRDs in our Kubernetes environment, then deployed the Operator along with its mutating and validating webhooks. Next, we rolled out a Collector configured to receive traces and export them to Coralogix. Finally, we applied the Instrumentation CRD, where we defined which instrumentation packages to use. Since most of our services are<em> </em><strong><em>Node.js</em></strong><em> </em>based, we focused on supporting them first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fR1qyUtgsuRpUpPTjp2U2g.png" /><figcaption>Example of our initial setup for the POC</figcaption></figure><p>Here’s a sample of the Instrumentation CRD we used 👇</p><pre>apiVersion: opentelemetry.io/v1alpha1<br>kind: Instrumentation<br>metadata:<br>  name: open-telemetry-instrumentation<br>spec:<br>  exporter: # Used by the application itself, and tells it where to expose the spans (Local Agent)<br>    endpoint: &quot;http://opentelemetry-collector.monitoring.svc.cluster.local:4317&quot;<br>  propagators:<br>    - tracecontext<br>    - baggage<br>  sampler:<br>    type: parentbased_traceidratio<br>    argument: &quot;1&quot; # 1.0 means 100% of traces<br> nodejs:<br>  image: &quot;ghcr.io/open-telemetry/opentelemetry-operator/autoinstrumentation-nodejs:0.53.0&quot;<br>  env:<br>    # Use gRPC for exporting traces<br>    - name: OTEL_EXPORTER_OTLP_PROTOCOL<br>      value: grpc<br>    # List of Node.js instrumentations to enable. You can add more as needed, If not set, all instrumentations will be enabled by default which may lead to CPU, and memory performance issues.<br>    # Source for instrumentations: https://github.com/open-telemetry/opentelemetry-js-contrib/blob/main/metapackages/auto-instrumentations-node/README.md#supported-instrumentations<br>    - name: OTEL_NODE_ENABLED_INSTRUMENTATIONS<br>      value: http,bunyan<br>    # Set the resource attributes for the Node.js instrumentation. This is useful for identifying the service in the telemetry data.<br>    - name: OTEL_NODE_RESOURCE_DETECTORS<br>      value: env,host,serviceinstance,container # os, and process were excluded for now as they consume more CPU and memory<br>    # Maximum number of spans to queue before sending them to the agent<br>    - name: OTEL_BSP_MAX_QUEUE_SIZE<br>      value: &#39;4096&#39;<br>    # Delay in milliseconds before the batch processor sends data to the agent<br>    - name: OTEL_BSP_SCHEDULE_DELAY<br>      value: &#39;5000&#39;</pre><p>The parentbased_traceidratio sampler we configured ensures consistent sampling across services. If a request already carries a trace ID, the sampler <em>honors</em> the parent span’s sampling decision—the decision made by the previous application the request passed through. If it’s a new trace, it falls back to the defined sampling ratio — in our case, 100%. This ensures we capture full, uninterrupted traces across all services.</p><pre>annotations:<br>  ...<br>  traffic.sidecar.istio.io/excludeOutboundPorts: ...,4317,4318<br>  instrumentation.opentelemetry.io/inject-nodejs: monitoring/opentelemetry-instrumentation</pre><p>Since some of our applications run with <strong><em>Istio</em></strong>, we added a specific pod annotation to exclude the ports used for exporting spans. We excluded both <strong>4317</strong> (gRPC) and <strong>4318</strong> (HTTP), as the Collector listens on those ports. One’s for gRPC, the other for HTTP — pick your poison. We chose <strong>gRPC</strong> because it fits perfectly with our needs for <strong>fast</strong>, efficient, and reliable communication between services.</p><p>We also added an annotation to enable auto-instrumentation. On deployment, or any other Controller restart, the pod is intercepted by the OTel-Operator <strong>mutating webhook</strong>, which updates it based on the defined Instrumentation CRD. In our case, we used inject-nodejs, with the corresponding opentelemetry-instrumentation resource created in the <strong>monitoring</strong> namespace.</p><p>As a result, the necessary instrumentation was automatically injected into the pod via an init-container, with no manual work needed from our developers. And just like magic, spans started flowing into Coralogix.</p><p>This was a big milestone for us — we immediately saw the potential to roll this out as a cross-engineering solution, and that’s exactly the kind of impact we were aiming for.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oYGTd0Lv1dHtm-NWzHa-Qg.png" /><figcaption>Visualizing a simple request flow</figcaption></figure><h3>How The Magic Happens?</h3><p>The magic behind auto-instrumentation lies in how the init-container is injected and what it does. When auto-instrumentation is enabled via pod annotations, the <strong>mutating webhook</strong> — part of the OpenTelemetry Operator — automatically updates the pod spec based on the instrumentation CRD to include an init-container. This container runs before the main app container starts and sets up the environment for tracing.</p><p>For Node.js services, it works by injecting the OpenTelemetry SDK and instrumentation packages into a shared volume. It then configures the app to preload these packages using the NODE_OPTIONS environment variable.</p><pre>- name: NODE_OPTIONS<br>  value: &gt;-<br>    --max_old_space_size=2800 --require<br>    /otel-auto-instrumentation-nodejs/autoinstrumentation.js</pre><p>Under the hood, it uses <strong>monkey patching</strong> — wrapping core modules (like http, bunyan, redis, etc) at runtime to capture spans automatically. No code changes required.</p><p>It’s fast, scalable, and lets us trace services out of the box.</p><h3>Tracing at Scale</h3><p>After the success of our POC, it was time to scale things up. We needed an architecture that could handle <strong>hundreds of services</strong>, <strong>multiple Kubernetes clusters</strong>, and do it all <strong>without overwhelming our systems or our engineers</strong>.</p><p>We started with <strong>two</strong> of our major EKS clusters and planned to expand into others as needed.</p><h4>The Cross-Cluster Challenge</h4><p>Now comes the tricky part — spans coming from agents in other clusters need to reach the centralized tail-sampling collectors in eks-1.</p><blockquote>💡 <em>In our examples, we’ll use the following clusters: </em><em>eks-1 will be our main cluster where tail-sampling is being made, and </em><em>eks-2 through </em><em>eks-n will be other clusters that export spans all the way to </em><em>eks-1. It’s worth noting that these don’t have to be EKS clusters. It can be any component capable of sending spans to a centralized tail-sampling service, which our services interact with</em></blockquote><p>We explored a few options:</p><ul><li><strong>Static list of tail-sampling collectors</strong> — Simple, but brittle. Any change means redeploying agents across clusters. Hard pass</li><li><strong>AWS Cloud Map</strong> — Dynamic, but adds new tech to our stack. Possible, but not now</li><li><strong>Middle layer of collectors</strong> — Acts as a proxy, forwarding spans to tail-sampling collectors in eks-1 via their headless service. We used a <strong>headless service</strong> between the balancing-layer collectors and the tail-sampling collectors to enable <strong><em>direct communication with individual tail-sampling collector pods</em></strong>. Unlike a regular Kubernetes SVC (which distribute load across apps), a headless service returns the full list of pod IPs, letting the middle layer use custom logic, like consistent hashing based on traceID, to <strong>ensure all spans from the same trace are routed to the same collector</strong></li></ul><p>We chose the <strong>middle-layer approach</strong>, with one key compromise: it increases cross-AZ traffic (since we don’t have AZ-aware routing yet). But it gave us dynamic routing, no service restarts, and confidence that <strong>all spans related to a trace ID will end up in the right tail-sampling collector</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*37Twk83apjtjpY0h2Q_3pg.png" /><figcaption>Cross-Cluster Architecture</figcaption></figure><h4><strong>Layer 1: Agents — The first stop for Spans</strong></h4><p>Each cluster runs a layer of lightweight <strong>agent Collectors</strong>. These are responsible for:</p><ul><li>Receiving spans from the instrumented apps via <a href="https://github.com/open-telemetry/opentelemetry-collector/tree/main/receiver/otlpreceiver">OTLP receiver</a></li><li>Performing initial head-sampling by filtering calls to /health and /metrics endpoints, enriching spans with Kubernetes attributes, masking sensitive data, and more</li><li>Forwarding spans to the next layer — either another collector acting like middleware, or directly to the backend provider</li></ul><p>These agents can be deployed as either a <strong>Deployment</strong> or a <strong>DaemonSet</strong>. While Deployments are lighter and easier to manage, we opted for <strong>DaemonSets</strong>. Why? Because in AWS, <strong>cross-AZ traffic isn’t free</strong>. DaemonSets ensure agents run on every node and keep traffic local — helping us reduce cross-AZ transfer costs <strong>unlike</strong> <strong>Deployments</strong> where locality can’t be guaranteed. This made them the most cost-effective and network-friendly option for us.</p><p>— — —</p><h4>Layer 2: Load-Balancing Collectors — Bridging the Clusters</h4><p>To support agents running <strong>outside</strong> of eks-1 cluster (like eks-2 through eks-n), we added a third layer: <strong>load-balancing collectors</strong>.</p><p>These collectors:</p><ul><li>Live inside eks-1 receive spans from remote agents via an <strong>Ingress endpoint</strong></li><li>Use the OpenTelemetry <a href="https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/exporter/loadbalancingexporter"><strong>load balancing exporter</strong></a> to hash spans by traceID and forward them to correct tail-sampling collector</li></ul><p>This approach ensures:</p><ul><li>All spans belonging to the same trace ID are routed to the same tail-sampling collector, ensuring the collector receives the complete trace and can make accurate sampling decisions</li><li><strong>Centralized, consistent tail-sampling logic is critical</strong> — if we implemented tail-sampling in multiple clusters without the load-balancing layer, we would end up with broken traces where some spans are sampled while others are dropped</li><li>No reliance on external service discovery or static configs</li></ul><p>This approach is essential because we have cross-cluster flows between services. While this approach increases cross-AZ traffic, the trade-off was worth it: we gained <strong>control, consistency</strong>, and the ability to support even <strong>components outside EKS</strong> — all while staying Kubernetes-native and restart-free.</p><pre>  exporters:<br>    loadbalancing:<br>      # &quot;routing_key&quot; - If no routing_key is configured, the default routing mechanism is traceID for traces<br>      timeout: 30s # In case a rolling-restart to the tail-sampling layer was made<br>      retry_on_failure:<br>        enabled: true<br>        initial_interval: 5s<br>        max_interval: 30s<br>        max_elapsed_time: 180s<br>      protocol:<br>        otlp:<br>          tls:<br>            insecure: false<br>      resolver:<br>        dns: # Notice to config a headless service in Kubernetes<br>          hostname: opentelemetry-tail-sampling-collector.monitoring.svc.cluster.local<br>          port: &quot;4317&quot; # gRPC port on the tail-sampling layer</pre><p>— — —</p><h4><strong>Layer 3: Tail Sampling Collectors — The Decision Makers</strong></h4><p>In our main cluster (eks-1), we deployed a centralized set of <strong>tail-sampling Collectors </strong>which use a dedicated <a href="https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/processor/tailsamplingprocessor">tail-sampling processor</a>. These handle:</p><ul><li>Aggregating all spans belonging to a trace</li><li>Making intelligent sampling decisions (e.g., keep only slow/error traces/ etc.)</li><li>Exporting selected traces to Coralogix using their dedicated <a href="https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/exporter/coralogixexporter">coralogix-exporter</a></li></ul><p>To make tail-sampling work properly, spans from all services are <strong>hashed by </strong><strong>traceID</strong> at the agent level, ensuring <strong><em>all parts of a trace land on the same collector</em></strong><em>—</em><strong><em>a must for tail-based sampling!</em></strong></p><pre>  tail_sampling:  # Tail sampling uses a first-match-wins strategy<br>    decision_wait: 60s<br>    policies:<br>      - name: contains_error # sample traces that contains an error, the full trace will be processed<br>        type: status_code<br>        status_code:<br>          status_codes:<br>            - ERROR<br>      - name: high_latency # sample traces that took at least 5 seconds, the full trace will be processed<br>        type: latency<br>        latency:<br>          threshold_ms: 5000<br>      - name: randomized # sample traces based on randomized percentage<br>        type: probabilistic<br>        probabilistic:<br>          sampling_percentage: 0.5</pre><p>This multi-layered setup gave us exactly what we needed: local span collection using <strong>DaemonSets</strong> to avoid cross-AZ traffic costs, a centralized tail-sampling layer to make informed decisions, and a scalable bridge for connecting multiple clusters without relying on static configurations or service restarts. It allowed us to roll out tracing across environments, support services both inside and outside of EKS, and stay fully aligned with our Kubernetes-native approach.</p><p>And the best part? Even when a request flows between services in different clusters, we still get the full trace. Since all spans eventually converge at the same tail-sampling collector, the full picture stays intact — no matter where the request travels.</p><blockquote>💡 I know this might feel a bit abstract right now, but don’t worry — we’ll break everything down with clear diagrams a little bit later</blockquote><h3>Rolling It Out</h3><p>The next challenge was clear: how do we actually adopt this across <strong>hundreds of microservices</strong> without opening 500+ merge-requests?</p><p>We couldn’t rely on manually adding pod annotations to every deployment — it would be painful, error-prone, and impossible to maintain at scale. So we introduced two key components to automate and centralize the configuration:</p><h4><strong>Resources Centralized Config</strong></h4><p>We created a new project which creates <strong>ConfigMap’s</strong> across every cluster/namespace, named resources-centralized-config. It contains template values and overrides (like CPU, Memory, Replicas and Opentelemetry configurations) which admission-control uses to mutate pods consistently across environments. This gave us a<strong> single place</strong> to control and update instrumentation settings.</p><pre>{<br> &quot;some-deployment&quot;: {<br>  &quot;cpu&quot;: &quot;100m&quot;,<br>  &quot;memory&quot;: &quot;256Mi&quot;,<br>  &quot;replicas&quot;: 6,<br>    &quot;opentelemetry&quot;: {<br>      &quot;tracing&quot;: {<br>        &quot;enabled&quot;: true,<br>        &quot;instrumentation_language&quot;: &quot;nodejs&quot;<br>      }<br>    }<br>  },<br>  &quot;some-statefulset&quot;: {<br>   ...<br>  }<br>}</pre><h4>Admission-Control</h4><p>To make this even smoother, we leveraged our in-house <a href="https://kubernetes.io/docs/reference/access-authn-authz/admission-controllers/">admission-control</a>. Whenever a Kubernetes controller — like a <em>Deployment</em>, <em>DaemonSet</em>, or <em>StatefulSet</em> - is created or restarted, the <strong>mutating webhook</strong> intercept it and forwards an admission review request to a dedicated endpoint in admission-control.</p><p>From there, it checks if that controller has a matching configuration defined in the resources-centralized-config ConfigMap, scoped by both <strong>cluster</strong> and <strong>namespace</strong>. If it finds a match, admission-control can automatically mutate the resource - updating fields like <strong>CPU</strong>, <strong>memory</strong>, <strong>replica count</strong>, and now also <strong>OpenTelemetry-related annotations and environment variables</strong>.</p><p>Once the resource is mutated with the relevant annotations, the <strong>OpenTelemetry Operator</strong> picks it up using it’s own mutating webhook, injects the required init-container, and just like that - <strong>spans start flowing</strong>.</p><pre>annotations:<br>  ...<br>  traffic.sidecar.istio.io/excludeOutboundPorts: ...,4317,4318<br>  instrumentation.opentelemetry.io/inject-nodejs: monitoring/opentelemetry-instrumentation</pre><p>This setup turned what could’ve been 500+ painful manual changes into a zero-touch rollout. By using namespace-level configs and centralized resource templates, we empowered teams to get tracing by default — no code changes, no extra work. Just consistent, scalable observability — baked right into the platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*Ik1S65rs3swFgxq1Yjr-uQ.png" /><figcaption>Full Tracing Flow</figcaption></figure><p>To populate the resources-centralized-config, we used a few simple kubectl commands to extract a list of target services across clusters and namespaces. This made it easy to define which workloads we wanted to instrument.</p><p>With everything wired up, it was time to start moving to production.</p><h3>Not so fast…</h3><p>Rolling out tracing to hundreds of services is exciting — but observability comes at a cost, especially in terms of <strong>performance, resource usage, and latency</strong>.</p><p>And when you’re in the <strong>payments industry</strong>, those things aren’t just nice-to-have — they’re <strong>mission-critical</strong>. Every millisecond counts. So before we even thought about going live, we had to be absolutely sure tracing wouldn’t introduce overhead that could impact our payment flows.</p><p><strong>So We Tested. A Lot.</strong></p><p>Using our in-house (and open-source) stress testing system, <a href="https://github.com/Zooz/predator"><strong>Predator</strong></a>, we ran extensive load tests to validate our tracing setup under real-world production conditions.</p><p>We focused on:</p><ul><li><strong>CPU, and Memory impact</strong> from injected OpenTelemetry SDKs</li><li><strong>Collector performance</strong> under high span throughput</li><li><strong>Tail-sampling stability</strong> at scale</li><li><strong>Latency impact</strong> on services critical to our payments flow</li><li><strong>Cross-AZ traffic</strong> patterns and cost optimizations</li><li><strong>Failure resilience</strong> — running chaos tests to observe how our applications behave when parts of the tracing system like agents, collectors, and OTel operator go down</li></ul><p>What We Learned:</p><ul><li>Tail-sampling, and head-sampling collectors required careful tuning (queue sizes, batching, memory limits, CPU, etc.) to stay responsive under load</li><li>A few high-throughput services initially showed CPU and memory spikes due to some heavy instrumentation libraries. We carefully audited our dependencies and <strong>removed memory- and CPU-intensive libraries that weren’t essential</strong> for our tracing goals. Ultimately, we decided to focus on tracing <strong>only the most critical libraries</strong> like http and bunyan, which gave us the insights we needed <strong>without the overhead</strong></li><li>Our decision to use <strong>DaemonSets</strong> for the agents was validated again — they kept span traffic local, reducing cross-AZ latency and cost</li><li>Even when parts of the tracing pipeline were taken down during the chaos tests, our pods continued to function without any impact. No crashes, no performance hits — exactly as we’d hoped</li></ul><p>In short: we had to check everything. Because in fintech, it’s not enough for tracing to work — it has to work without slowing you down.</p><h3>Wrapping It Up</h3><p>Implementing distributed tracing at scale is no easy task — especially when dealing with multiple Kubernetes clusters and hundreds of microservices. Our experience taught us that while OpenTelemetry and the Operator provide powerful building blocks, the real work lies in designing a system that’s scalable, maintainable, and low-impact on performance.</p><p>By centralizing configuration and automating mutations through admission-control, we eliminated the need for manual changes across hundreds of deployments. Our multi-layered collector architecture ensured tracing data flows efficiently across clusters, while smart sampling strategies helped us avoid system overload.</p><p>We also learned the importance of thorough testing. Chaos experiments and resource profiling confirmed that tracing wouldn’t degrade the performance or reliability of our most critical payment flows.</p><p>Ultimately, this gave our engineers clear visibility into production traffic. They can now <strong>correlate logs with trace IDs</strong>, <strong>understand complete request flows</strong>, and <strong>see how errors propagate through services</strong>. It’s no longer a guessing game — we finally see how our system behaves in the real world: which services depend on which, where the real bottlenecks are, and how issues impact downstream consumers.</p><p><strong><em>Tracing isn’t just a debugging tool — it’s a window into your system’s true behavior. With OpenTelemetry, we’re not just tracking requests, we’re revealing architecture, uncovering patterns, and unlocking better engineering decisions.</em></strong></p><p>And the best part? It does all this without adding extra burden on development teams.</p><blockquote><em>💡 We also want to emphasize: Every newly instrumented service must pass a stress test to ensure tracing doesn’t introduce performance degradation. On top of that, we run </em><strong><em>nightly stress tests</em></strong><em> to catch regressions and make sure nothing breaks silently.</em></blockquote><blockquote><em>Some teams might choose to go beyond basic instrumentation like </em><em>http and </em><em>bunyan, </em><a href="https://www.npmjs.com/package/@opentelemetry/auto-instrumentations-node"><em>using additional packages</em></a><em> — but those need to be handled with care, as they can impact CPU and memory usage. Instrumentation is powerful, but like any power tool, it needs to be used carefully.</em></blockquote><p>If you’re considering distributed tracing, start small. Build a proof of concept, automate everything you can, and focus on actionable insights. That’s how observability becomes a force multiplier — not just another tool.</p><p>And one more thing. We didn’t even get into — <strong>observability of the observability system</strong>. A lot of effort went into building Grafana dashboards, defining alerts, and collecting metrics to monitor the tracing pipeline itself. From Grafana panels that track span throughput and latency, to alerts on queue sizes and dropped spans — we’ve made sure the system that watches everything can be watched too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oWaCbWzykh9ckWq3bGtKvA.png" /><figcaption>Sneak peek to our Opentelemetry Overview dashboard</figcaption></figure><h3>What’s Next?</h3><p>While we’ve come a long way, the journey doesn’t stop here. We’re actively exploring <strong>smarter tail-sampling strategies</strong> to get even more value out of the data we collect — without overwhelming our systems.</p><p><strong>Cost-efficiency remains a key focus</strong> as well: even with DaemonSet agents helping reduce cross-AZ traffic, spans still cross availability zones. We’re working on <strong>AZ-aware routing</strong> strategies to keep traffic local and cut down on unnecessary data transfer costs.</p><p>While <strong>Node.js was our starting point</strong>, it’s only one piece of our tech stack. We’re now expanding tracing support to services written in <strong>Java, Go, and beyond</strong>, ensuring full coverage across our ecosystem.</p><p>We’re also looking beyond Kubernetes. Some systems live outside the cluster, and we want to bring <strong>consistent tracing across all environments</strong>, regardless of where the service runs.</p><p>In short: there’s still plenty left to build, optimize, and improve.</p><h3>Final Words</h3><p>If you’ve made it this far — thank you. This was a deep dive into something that started as a small POC and turned into a production-grade, cross-cluster tracing architecture.</p><p>We kicked things off small, but scaling this up was truly a team effort. Massive thanks to <a href="https://www.linkedin.com/in/shai-halfon96/">Shai Halfon</a> and <a href="https://www.linkedin.com/in/niv-raviv/">Niv Raviv</a>, who took the design to the next level and made sure we could support tracing at scale without losing our minds. Shoutout to <a href="https://www.linkedin.com/in/adi-ophir-63a259134/">Adi Ophir</a>, and <a href="https://www.linkedin.com/in/hany-mahajna-8081a642/">Hany Mahajna</a> for implementing the resources-centralized-config—a critical piece that allowed us roll this out across hundreds of services without breaking anything. And of course, <a href="https://www.linkedin.com/in/jacob-koren-37370066/">Jacob Koren</a>, who always knew how to turn tough question marks into exclamation marks.</p><p><strong>This project reminded us that while tools like OpenTelemetry are powerful, it’s the team that makes them work.</strong></p><p>Thanks for reading, happy tracing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=294d9775b2d0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/payu-engineering/trace-me-if-you-can-our-opentelemetry-journey-294d9775b2d0">Trace Me If You Can: Our Opentelemetry Journey</a> was originally published in <a href="https://medium.com/payu-engineering">payu-engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking the Power of Debezium]]></title>
            <link>https://medium.com/payu-engineering/unlocking-the-power-of-debezium-69ce9170f101?source=rss-9a3810d92c03------2</link>
            <guid isPermaLink="false">https://medium.com/p/69ce9170f101</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[change-data-capture]]></category>
            <category><![CDATA[debezium]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Tomer Guttman]]></dc:creator>
            <pubDate>Sun, 20 Aug 2023 11:04:41 GMT</pubDate>
            <atom:updated>2023-08-20T11:38:52.537Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This blog post aims to share our experience, and insights with Debezium (CDC Tool), and the development phases we went through to improve reliability, and observability while capturing data changes in our system.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*xMVxnzC6-heGXrHpOr6jVw.png" /></figure><h3>Why Debeizum?</h3><p>What reasons might drive you to integrate this tool as a part of your system?</p><p>In our platform, we use Cassandra as our main database to achieve scalability and low latency. While Debezium does offer CDC capabilities for Cassandra, we decided against its usage due to the distributed nature of Cassandra— it would mean having Debezium installed on every separate Cassandra node.</p><p>However, as we started implementing our <strong>Treasury</strong> platform, which demanded <strong>ACID</strong> support, we shifted to MySQL. Subsequently, we re-evaluated the suitability of a CDC solution, leading us to select Debezium.</p><p>Debezium offers a solution for <strong>capturing</strong> and <strong>reacting</strong> to real-time changes in your system’s databases. By seamlessly connecting to various database engines, such as MySQL, PostgreSQL, MongoDB, and more.</p><p>Debezium enables you to monitor and capture every database transaction as a stream of events. This provides valuable insights into your application’s data changes, making it ideal for use cases like <strong>real-time analytics</strong>, <strong>data synchronization</strong>, <strong>monitoring</strong>, and building <strong>event-driven, and performant architectures</strong>.</p><h3>Introduction</h3><p>Let’s begin by explaining what Debezium is, and getting a grasp of the concept of CDC.</p><p>CDC, which stands for Change Data Capture, is a software pattern used to monitor and capture data changes, allowing other software to respond accordingly.</p><p>This process involves capturing changes at the row level within database tables and then streaming these changes to a data-streaming platform like Kafka. This enables consumers to access these streams of change events in the chronological order in which they occurred, empowering them to take appropriate actions based on the changes.</p><p>Before diving into the flow when using Debezium, there are several terms that require our understanding:</p><ol><li><strong>Binlog</strong> — Binary log (binlog) in MySQL is a chronological record of data changes, capturing all write operations performed on the database, essential for replication, point-in-time recovery, and data integrity. Binlog also has <strong>retention</strong>, which determines how long logs are kept, balancing recovery needs with storage efficiency</li><li><strong>Debezium Server</strong> — Debezium provides a ready-to-use application that streams change events from a source database to messaging infrastructure like Kafka. For streaming change events to Kafka, we deploy Debezium connectors via Kafka Connect</li><li><strong>Debezium Connector</strong> — The Debezium connector reads the binlog, produces change events for row-level INSERT, UPDATE, and DELETE operations, and emits the change events to Kafka topics</li><li><strong>Kafka </strong>— High-throughput, distributed, publish-subscribe messaging queue system that efficiently handles real-time data streams, making it ideal for event-driven architectures and big data processing</li><li><strong>Kafka Consumers</strong> — Kafka Consumers process real-time data within Kafka, enabling transformations through stream processing while seamlessly integrating with Kafka’s model. It simplifies building scalable, and fault-tolerant data pipelines</li></ol><p>Now that we became familiar with the core components, let’s see how data flows inside our system using Debezium.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GQK5tmDaZecPdrE1nLLklQ.jpeg" /><figcaption>Data pipeline flow when using Debezium</figcaption></figure><p>Our MySQL database has a binlog that stores data changes from all the tables in it. Within these changes lies data from a specific table that we want to monitor.</p><p>To capture its changes, we’ve set up a Debezium connector specifically configured to capture changes occurring within this table.</p><p>Once a change is detected, the connector captures it and sends that data to a dedicated Kafka topic. Later, our Kafka streams/ consumers retrieve this data from the designated topics, enhancing and modifying it as required, before exporting it to other components such as Snowflake, Elasticsearch, etc.</p><h3>Configurations, and more Configurations</h3><p>Once Debezium is deployed within the environment, this is where the fun starts.</p><p>To begin capturing changes in a database, you will need to create a Debezium connector.</p><p>It’s worth noting that the implementation of each connector type varies based on the database in use. While we’re using the MySQL connector, the key takeaway is understanding the concept of a “connector” rather than the specific implementation details.</p><p>The following is an example of a basic connector configuration <strong>we had when initially adopting Debezium</strong> (v1.6).</p><pre>{<br>   &quot;name&quot;:&quot;debezium-packages-connector-sandbox&quot;,<br>   &quot;connector.class&quot;:&quot;io.debezium.connector.mysql.MySqlConnector&quot;,<br>   &quot;include.schema.changes&quot;:&quot;false&quot;,<br>   &quot;decimal.handling.mode&quot;:&quot;precise&quot;,<br>   &quot;transforms&quot;:&quot;Reroute,unwrap&quot;,<br>   &quot;transforms.unwrap.type&quot;:&quot;io.debezium.transforms.ExtractNewRecordState&quot;,<br>   &quot;transforms.Reroute.type&quot;:&quot;io.debezium.transforms.ByLogicalTableRouter&quot;,<br>   &quot;transforms.Reroute.topic.regex&quot;:&quot;(.*)payouts_sandbox_qa(.*)&quot;,<br>   &quot;transforms.Reroute.topic.replacement&quot;:&quot;packages_sandbox&quot;,<br>   &quot;transforms.unwrap.add.fields&quot;:&quot;&quot;,<br>   &quot;database.server.name&quot;:&quot;packages_sandbox&quot;,<br>   &quot;database.user&quot;:&quot;**********&quot;,<br>   &quot;database.server.id&quot;:&quot;**********&quot;,<br>   &quot;database.port&quot;:&quot;**********&quot;,<br>   &quot;database.hostname&quot;:&quot;**********&quot;,<br>   &quot;database.password&quot;:&quot;**********&quot;,<br>   &quot;database.history.kafka.bootstrap.servers&quot;:&quot;**********&quot;,<br>   &quot;database.history.kafka.topic&quot;:&quot;debezium_history_packages_sandbox&quot;,<br>   &quot;database.whitelist&quot;:&quot;payouts_sandbox_qa&quot;,<br>   &quot;table.whitelist&quot;:&quot;payouts_sandbox_qa.packages&quot;,<br>   &quot;snapshot.mode&quot;:&quot;initial&quot;,<br>   &quot;snapshot.new.tables&quot;:&quot;parallel&quot;<br>}</pre><p>Since most of the fields are self-explanatory, we’ll focus on explaining the significant ones:</p><ol><li>database.whitelist- Comma-separated list of regular expressions that match the names of the databases for which to capture changes. The connector does not capture changes in any database whose name is not in database.whitelist</li><li>table.whitelist — Comma-separated list of regular expressions that match fully-qualified table identifiers of tables whose changes you want to capture</li><li>transforms.Reroute.topic.regex — Regular expression that the transformation applies to each change event record to determine if it should be routed to a particular topic</li><li>transforms.Reroute.topic.replacement — Regular expression that represents the destination topic name. The transformation routes each matching record to the topic identified by this expression</li></ol><p>Put simply, we are configuring the packages-connector to establish a connection to the payouts_sandbox_qa database, and track changes in payouts_sandbox_qa.package table. When it identifies changes, it checks if they originated from a table matching the regex pattern (.*)payouts_sandbox_qa(.*) and if they do, these changes are then exported to a Kafka topic named packages_sandbox.</p><p>More detailed explanations about the remaining fields can be found in the Debezium documentation, available at this link — <a href="https://debezium.io/documentation/">here</a>.</p><h3>What we can do with all that data?</h3><p>With Debezium up and running, along with a configured connector exporting events to Kafka from our table, we are now able to consume these events and take actions as needed.</p><p>In our case, we export our data to two primary destinations:</p><ol><li><strong>Elasticsearch</strong> 🔍 — We consume the events, enrich them with additional data from different services in our system, and then export them to Elasticsearch. This enables us to efficiently search and access them through our UI.</li><li><strong>Snowflake</strong> ❄️ — We consume the events and then export the data to Snowflake, our cloud-based big data tool. Snowflake mainly serves as a platform for generating a variety of reports for our merchants, such as settlement, payment, and other types of reports.</li></ol><p>These are just two examples from our system, but the possibilities for what can be done with the data are endless.</p><h3>Not as easy as it seems</h3><p>Our company was among the early adopters of Debezium, which led us to face several challenges throughout the process. However, over time, we grew more confident and gained a deeper understanding of the necessary steps we had to make in order to improve our Debezium implementation.</p><p>We encountered a few minor issues, often originating from misconfigured connectors. However, the most important topic we’ll discuss is when a <strong>connector loses its binlog offset</strong>.</p><p>As mentioned earlier, every connector can be configured to capture changes for specific tables within the database. The way this works is that the connector captures changes associated with that particular table <strong>within the binlog</strong>.</p><p>After capturing the changes, the connector stores the most recent offset in a dedicated Kafka topic, in our case we named it debezium_connect_offsets.</p><p>As seen in the Kafka UI screenshot below, within the specific topic dedicated to Debezium offsets, we can see that the most recent offset message for the packages_sandbox connector is listed as 1435109 (pos).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eGc2c76KEX0abRSA-cUHMQ.png" /><figcaption>Offset message of “packages” connector, storing its latest recorded offset</figcaption></figure><p>It is crucial to understand the following:</p><ol><li>A binlog contains changes from all the tables within MySQL, not only from the tables we’ve configured the connector to capture changes for</li><li>MySQL also has a <strong>binlog retention setting</strong>, which means that after a specified period of time, such as 7 days, the binlog rotates. It means that changes that were recorded within it, are no longer available.</li></ol><p>How do these two factors come together? Let me share an example.</p><p>Consider packages table. We created a dedicated connector for it, named packages-connector, and configured it to capture changes from it. However, packages the table is characterized by <strong>low traffic</strong>. In other words, records aren’t added to the table on a daily basis, maybe a few times a month.</p><p>Despite the infrequent changes, these changes when they occur, are extremely important for us, and it’s imperative that we avoid missing any of them.</p><p>So, packages-connector runs over the course of a few days, successfully capturing changes from the packages table as expected. Then, it stores the most recent offset it recorded as 1435109. Now, let&#39;s assume that the activity in packages table comes to a halt.</p><p>During this period of inactivity, a complication arises from the continuous progression of binlog offsets. This progression is occurring due to changes taking place in other tables, which are also being logged to the binlog, and the binlog data is starting to rotate.</p><p>After a period of two weeks, no updates or inserts were made to the packages table.</p><p>Suddenly our MySQL connection disrupts, resulting in the restart of Debezium due to the loss of its connection to MySQL.</p><p>After Debezium restarts successfully, the packages-connector is trying to determine the last point at which it captured a change, to see if it potentially missed data changes during the downtime. Meanwhile, it throws an unexpected error.</p><pre>io.debezium.DebeziumException: The connector is trying to read binlog starting at SourceInfo [...], but this is no longer available on the server.</pre><p>It attempts to locate the offset 1435109 within the binlog, but discovers that this offset does not exist as a result of the binlog’s rotation during the two-week period.</p><p>Not knowing what to do in this situation, the connector throws an exception and goes down.</p><p>This presents a major issue. It means that events occurring right now in packages table remain unrecorded during the period when packages-connector is down.</p><p>The only way to recover from this is to manually run a full snapshot of the database (using snapshot mode — when_needed, additional information about snapshots can be seen <a href="https://debezium.io/documentation/reference/stable/connectors/mysql.html#mysql-property-snapshot-mode">here</a>).</p><p>As a snapshot is generated, the connector <strong>locks</strong> all tables it has been configured to monitor for changes. This is something we try to avoid due to the possible performance impact it could introduce on our database.</p><p>As a result, customers might miss out on data associated with new resources created/ updated in the packages table. <strong>This is a situation that we cannot allow</strong>, and what makes it even worse is that we might not even be aware that this issue is occurring due to a <strong>lack of observability</strong>.</p><h3>Improving Reliability and Observability</h3><p>As time went by, we began to notice connectors losing offsets in our production environment.</p><p>This drove us to search for a solution that could improve the reliability and observability of our Debezium components.</p><p>Following a thorough research, we eventually discovered the necessary steps to resolve the issues we encountered.</p><h4>Observability</h4><p><strong><em>Logging</em></strong></p><p>Coralogix serves as our primary logging platform, the original structure of Debezium logs was composed of lengthy, unparseable strings.</p><p>To enable effective searching in Coralogix we had to transform the logs into JSON objects.</p><p>Debezium uses log4j library (don’t worry, it’s after the vulnerability was addressed). To configure its logger we needed to overwrite the log4j.properties file, which defines the logs format.</p><pre># This file will override the default configuration of logs format<br><br>kafka.logs.dir=logs<br><br>log4j.rootLogger=INFO, stdout, appender<br><br># Disable excessive reflection warnings - KAFKA-5229<br>log4j.logger.org.reflections=ERROR<br><br>log4j.appender.stdout=org.apache.log4j.ConsoleAppender<br>log4j.appender.stdout.threshold=INFO<br>log4j.appender.stdout.layout=org.apache.log4j.PatternLayout<br>log4j.appender.stdout.layout.ConversionPattern={&quot;timestamp&quot;:&quot;%d{ISO8601}&quot;,&quot;level&quot;:&quot;%p&quot;,&quot;thread&quot;:&quot;%t&quot;,&quot;logger&quot;:&quot;%c&quot;,&quot;message&quot;:&quot;%m&quot;,&quot;connector_type&quot;:&quot;%X{dbz.connectorType}&quot;,&quot;connector_name&quot;:&quot;%X{dbz.connectorName}&quot;,&quot;connector_context&quot;:&quot;%X{dbz.connectorContext}&quot;}%n<br><br><br>log4j.appender.appender=org.apache.log4j.DailyRollingFileAppender<br>log4j.appender.appender.DatePattern=&#39;.&#39;yyyy-MM-dd-HH<br>log4j.appender.appender.File=${kafka.logs.dir}/connect-service.log<br>log4j.appender.appender.layout=org.apache.log4j.PatternLayout<br>log4j.appender.appender.layout.ConversionPattern={&quot;timestamp&quot;:&quot;%d{ISO8601}&quot;,&quot;level&quot;:&quot;%p&quot;,&quot;thread&quot;:&quot;%t&quot;,&quot;logger&quot;:&quot;%c&quot;,&quot;message&quot;:&quot;%m&quot;,&quot;connector_type&quot;:&quot;%X{dbz.connectorType}&quot;,&quot;connector_name&quot;:&quot;%X{dbz.connectorName}&quot;,&quot;connector_context&quot;:&quot;%X{dbz.connectorContext}&quot;}%n</pre><p>As you can see, the ConversionPattern modification is the main and only change. Once this file is overwritten, our logs became searchable through Coralogix. This simplified our debugging and made our life much easier.</p><p>Additional information about logging can be seen <a href="https://debezium.io/documentation/reference/stable/operations/logging.html">here</a>.</p><p>Below, you can observe our latest JSON logs being displayed in Coralogix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VKAfJuBQ737WTmfu6k8LMQ.png" /><figcaption>Debezium logs in JSON format, as presented in Coralogix</figcaption></figure><p>— —</p><p><strong><em>Metrics</em></strong></p><p>We also discovered that Debezium had introduced in their <a href="https://debezium.io/documentation/reference/stable/operations/monitoring.html">documentation</a> a way to monitor it. This involves the usage of JMX metrics provided by Kafka, which can be later on exported to <strong>Prometheus</strong> and <strong>Grafana</strong>.</p><p>Since we were already using <strong>Prometheus</strong> and <strong>Grafana</strong> we immediately jumped on the catch.</p><p>We then set up <strong>alerts</strong> for all of our connectors and also updated our Grafana Debezium <strong>dashboards.</strong> This allowed us to have a real-time overview of our connector statuses, and in the event of any downtime, we immediately know about it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o3F6xfEcIHQHxoVR41WaeA.png" /><figcaption>Debezium dashboard in Grafana showing all of our connectors’ statuses</figcaption></figure><p>Below is an example of a PromQL (Prometheus Querying Langauge) definition for an indicator of one of our connectors. It’s straightforward yet effective. If the connector is up and running it returns one, if it’s down or doesn’t even exist, it will return a zero.</p><p>With this indicator in place, we could easily create an alert by checking if its query result is not equal to one.</p><pre>sum(debezium_metrics_Connected{context=&quot;streaming&quot;, env=&quot;eks-prd-apps&quot;, name=~&quot;balances_test_incoming_operation.*&quot;}) or vector(0)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lOpxkNdDxNX1iRaxWSxZcg.png" /><figcaption>The result of the query above after being executed</figcaption></figure><p>Now, after the alerts were set in place. If an alert is triggered by one of our connectors, we will receive a notification immediately in our Slack channel. An example of an alert in our channel can be seen below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*vF-O7w7OFL65LwhPAzzrZw.png" /><figcaption>Slack notification we received due to the alert</figcaption></figure><h4>Reliability</h4><p>This is where the advanced concepts are coming into play.</p><p>We continued to face the problem of <strong>connectors losing binlog offsets</strong>. This issue occurred in both production and test environments, particularly when we configured connectors to capture changes from <strong>low-traffic</strong> tables.</p><p>Debezium already had a heartbeat logic in place (v1.6), but it didn’t help us. This is because the existing heartbeat was focused on Kafka, rather than the database itself.</p><p>However, luck was on our side, as in later versions a new field was introduced: heartbeat.action.query, and this is what it does —</p><blockquote><strong>“Specifies a query that the connector executes on the source database when the connector sends a heartbeat message”</strong></blockquote><p><strong>This is exactly what we needed</strong> for our low-traffic connectors. However in order to make use of it, we needed to upgrade, since this field wasn’t supported in our current version.</p><p>We decided to upgrade Debezium and go through the breaking changes. Despite encountering multiple challenges during that process, eventually, with sweat and tears, we managed to do it and upgraded to ✨ v2.3.0 ✨, which is the most recent release at the time of writing this blog post.</p><p><strong><em>Needless to say, we were thrilled with the outcome!</em></strong></p><p>Now, In order to solve the offset problem, we decided on the following.</p><p>For each microservice with a table from which we were capturing changes, we created a dedicated table named debezium_heartbeat. This table is reserved for the heartbeat.action.query that we planned to configure for each connector.</p><p>The MySQL definition of debezium_heartbeat table is as follows:</p><pre>CREATE TABLE IF NOT EXISTS debezium_heartbeat (<br>    id BIGINT AUTO_INCREMENT PRIMARY KEY,<br>    connector_name VARCHAR(255) NOT NULL,<br>    last_heartbeat TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),<br>    UNIQUE KEY connector_name_index (connector_name)<br>);</pre><p>When the heartbeat is triggered, it will initiate the execution of the following query:</p><pre>INSERT INTO &lt;database_name&gt;.debezium_heartbeat (connector_name, last_heartbeat) VALUES (&#39;&lt;connector_name&gt;&#39;, NOW()) ON DUPLICATE KEY UPDATE last_heartbeat = NOW()</pre><p>At the same time, we reconfigure our connectors to capture changes from two tables — the original table but also changes of the debezium_heartbeat table.</p><p>With heartbeat set to occur once an hour, we can be certain that the connector’s offset will remain up-to-date — This is due to the connector capturing changes from both tables, effectively storing the latest offset out of both within the binlog.</p><p>Our connector configuration now looks as such in v2.3.0.</p><pre>{<br>   &quot;name&quot;:&quot;debezium-packages-connector-sandbox&quot;,<br>   &quot;connector.class&quot;:&quot;io.debezium.connector.mysql.MySqlConnector&quot;,<br>   &quot;topic.heartbeat.prefix&quot;:&quot;debezium_heartbeat&quot;,<br>   &quot;topic.prefix&quot;:&quot;packages_sandbox&quot;, // previously &quot;database.server.name&quot;<br>   &quot;include.schema.changes&quot;:&quot;false&quot;,<br>   &quot;decimal.handling.mode&quot;:&quot;precise&quot;,<br>   &quot;transforms&quot;:&quot;Reroute,unwrap&quot;,<br>   &quot;transforms.unwrap.type&quot;:&quot;io.debezium.transforms.ExtractNewRecordState&quot;,<br>   &quot;transforms.Reroute.type&quot;:&quot;io.debezium.transforms.ByLogicalTableRouter&quot;,<br>   &quot;transforms.Reroute.topic.regex&quot;:&quot;(.*)payouts_sandbox_qa.(.*)&quot;,<br>   &quot;transforms.Reroute.topic.replacement&quot;:&quot;$2_sandbox&quot;,<br>   &quot;transforms.unwrap.add.fields&quot;:&quot;&quot;,<br>   &quot;database.user&quot;:&quot;**********&quot;,<br>   &quot;database.server.id&quot;:&quot;**********&quot;,<br>   &quot;database.port&quot;:&quot;**********&quot;,<br>   &quot;database.hostname&quot;:&quot;**********&quot;,<br>   &quot;database.password&quot;:&quot;**********&quot;,<br>   &quot;database.include.list&quot;:&quot;payouts_sandbox_qa&quot;, // previously &quot;database.whitelist&quot;<br>   &quot;table.include.list&quot;:&quot;payouts_sandbox_qa.packages,payouts_sandbox_qa.debezium_heartbeat&quot;, // previously &quot;table.whitelist&quot;<br>   &quot;schema.history.internal.kafka.bootstrap.servers&quot;:&quot;**********&quot;, // previously &quot;database.history.kafka.bootstrap.servers&quot;<br>   &quot;schema.history.internal.kafka.topic&quot;:&quot;debezium_history_packages_sandbox&quot;, // previously &quot;database.history.kafka.topic&quot;<br>   &quot;heartbeat.interval.ms&quot;:&quot;3600000&quot;,<br>   &quot;heartbeat.action.query&quot;:&quot;INSERT INTO payouts_sandbox_qa.debezium_heartbeat (connector_name, last_heartbeat) VALUES (&#39;debezium-packages-connector-sandbox&#39;, NOW()) ON DUPLICATE KEY UPDATE last_heartbeat = NOW()&quot;,<br>   &quot;snapshot.mode&quot;:&quot;initial&quot;,<br>   &quot;snapshot.new.tables&quot;:&quot;parallel&quot;<br>}</pre><p>The graph below offers a better grasp of how the connector offsets are updated within Kafka as a result of the hourly execution of the heartbeat query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TkHi00tkmuLHx0wAV1kMKA.jpeg" /><figcaption>The execution of the heartbeat query triggers a capturing event on the “debezium_heartbeat” table. Consequently, this event leads to an update in the dedicated offset topic.</figcaption></figure><p>We can see that we are now capturing changes from two tables, that are part of the same database</p><ol><li>payouts_sandbox_qa.packages</li><li>payouts_sandbox_qa.debezium_heartbeat</li></ol><p>Those who have sharp eyes out there will notice that adjustments were made to transforms.Reroute.topic.regex and transforms.Reroute.topic.replacement.</p><p>In our current configuration for capturing changes from two separate tables, our goal is to ensure that the connector exports events from each table to its dedicated Kafka topic. This can be achieved by utilizing a<strong> group regex pattern</strong> structured as follows: (.*)payouts_sandbox_qa.(.*).</p><p>This means that when a change is captured within one of the tables, the following scenarios will take place:</p><ol><li>Change in payouts_sandbox_qa.packages → $1 will be set as an empty string, and $2 will be set as packages, resulting in the event being routed to the packages_sandbox topic</li><li>Change in payouts_sandbox_qa.debezium_heartbeat → $1 will be set as an empty string, and $2 will be set as debezium_heartbeat, resulting in the event being routed to the debezium_heartbeat_sandbox topic</li></ol><blockquote><em>Given that </em><em>packages_sandbox topic is already created in Kafka, it’s important to understand that the heartbeat topics must be created prior to this change. Otherwise Debezium will throw an error.</em></blockquote><blockquote><em>Furthermore, additional topics must be created, as Debezium also sends Kafka messages to the following topic:</em></blockquote><blockquote><em>__debezium-heartbeat.&lt;topic.prefix&gt;</em></blockquote><p>Summarizing the reliability section, we’ve introduced a connector designed to capture changes from two tables. Its offset is updated hourly through the heartbeat logic we’ve put in place, ensuring that the offset remains up-to-date.</p><p>Moreover, this connector exports events to two distinct Kafka topics: one for the heartbeats and the other for the packages.</p><p>We’ve implemented this approach across all our connectors, guaranteeing the retention of offsets for an extended duration.</p><p>This assurance not only maintains the seamless operation of our connectors, but also enables them to effortlessly recover even in the event of an unexpected Debezium restart.</p><h3>Conclusion</h3><p>I’ll make an effort to provide you with some of the valuable insights I’ve acquired during this journey:</p><ol><li>Debezium is a complex component that should not be underestimated. I’ve touched on only a fraction of the topics, there is much more to Debezium such as snapshot modes, transformations, security features, etc. It requires attention and care, and the learning curve takes time. However, once you master it, you’ll realize how <strong>powerful</strong> it is</li><li>The <strong>community</strong> plays a vital role. I discovered a dedicated Debezium forum where knowledge is freely shared, and questions are addressed daily. This resource proved invaluable to us along the journey (link to the forum — <a href="https://debezium.zulipchat.com/">https://debezium.zulipchat.com</a>).</li><li>The Debezium <strong>documentation</strong> is comprehensive, so it’s important to conduct thorough searches across the various sections. Make sure to select the version you’re using and the specific connector type related to your database. Many times, we confronted challenges that were eventually covered in the documentation (link to the documentation — <a href="https://debezium.io/documentation">https://debezium.io/documentation</a>)</li><li>In addition, maintaining close relationships with your <strong>peers</strong> is crucial, especially with the operations and data teams. Our journey wouldn’t have been possible without their expertise and guidance, especially during the upgrade process and when understanding data pipelines. Their insights helped us avoid mistakes and were truly invaluable</li><li>I strongly recommend using a <strong>Monorepo</strong> that consolidates all your connectors within a single project. If you’re dealing with multiple connectors, adopting a Monorepo approach can significantly simplify your workflow — take my word for it!</li></ol><p>I hope you’ve made it this far through the blog post. I understand that it’s been quite an extensive read, but I’m mindful that there could be someone out there on our beautiful planet who is currently wrestling with Debezium, perhaps attempting to address challenges similar to the ones we’ve explored here.</p><p>If this blog post helps them overcome these obstacles, it would be genuinely satisfying to help a fellow engineer.</p><p>Meanwhile, if you found this blog post intriguing or beneficial, don’t hesitate! Feel free to leave a like, comment, and subscribe. Of course, if any questions come to mind after reading this, I’ll be sure to answer them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69ce9170f101" width="1" height="1" alt=""><hr><p><a href="https://medium.com/payu-engineering/unlocking-the-power-of-debezium-69ce9170f101">Unlocking the Power of Debezium</a> was originally published in <a href="https://medium.com/payu-engineering">payu-engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How we managed to monitor scheduled events in our system]]></title>
            <link>https://medium.com/payu-engineering/how-we-managed-to-monitor-scheduled-events-in-our-system-91930e6992e6?source=rss-9a3810d92c03------2</link>
            <guid isPermaLink="false">https://medium.com/p/91930e6992e6</guid>
            <category><![CDATA[metrics]]></category>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[slo]]></category>
            <dc:creator><![CDATA[Tomer Guttman]]></dc:creator>
            <pubDate>Thu, 13 Oct 2022 08:16:31 GMT</pubDate>
            <atom:updated>2022-10-18T15:36:49.892Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This blog post aims to share a problem we encountered while implementing SLOs to measure scheduled events in our reporting system, and how we managed to solve it</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RJsGXDw_hY0j5wIGAhGNvQ.png" /></figure><h3>Introduction</h3><p>It hasn’t been that long ago that terms such as <a href="https://prometheus.io/">Prometheus</a>, <a href="https://go2.grafana.com/">Grafana</a>, <a href="https://sre.google/sre-book/service-level-objectives/">SLIs/ SLOs</a>, Metrics, and Alerts were just buzzwords to me, but then I received a task that made it all clear.</p><p>It’s been a while that I’ve been working on different components in our reports system, and I started noticing a few reliability issues:</p><ol><li>Currently, we won’t be aware if a scheduled report isn’t created on time/ not created at all for a customer.</li><li>We experienced report failures in production due to frequent changes to our queries.</li><li>We had to improve our visibility using metrics to measure the success/ failure of reports.</li></ol><p>I quickly raised a red flag. In the next quarter, I was assigned multiple tasks to solve them, a taste of my own medicine you can call it.</p><p>Surprised the tasks were prioritized so quickly, I was extremely motivated to start digging into these issues.</p><h3>Motivation</h3><p>Reports play a crucial role in the reconciliation process for our customers. By using reports we give our customers the ability to review their funds and transactions over a specified period of time.</p><p>Furthermore, it enables our customers to analyze unauthorized transactions/frauds, accounting errors, payment status/amount mismatches, and more.</p><p>These reliability issues had to be addressed due to the importance of the reports to our customers.</p><p>We decided to implement thorough end-to-end tests and create multiple alerts for better visibility in our production environment.</p><p>Tests were the easy part, but in order to implement alerts — we had to gather some metrics first. Usually, metrics are pretty straightforward, but when talking about <em>measuring</em> metrics of scheduled events (that can occur weeks/ months from now), this is where it gets a bit tricky — but we were up for the challenge.</p><p>Despite spending countless hours searching the internet for a lead on how to measure metrics of scheduled events, I came up short. It was very weird since I thought to myself — <strong><em>Big companies must have scheduled events in their system, how do they monitor it?</em></strong> I didn’t find out, so we had to design our own solution.</p><h3>Terminology</h3><p>Before diving in, let’s start with a few terms we need to understand.</p><h4>Reports</h4><p>We have two ways to generate reports in our system:</p><ol><li>Ad-hoc (on-demand) reports — Can be generated with a click of a button and are received within a few minutes.</li><li>Scheduled reports — Being created via a scheduled async flow where you can specify the frequency of the report.</li></ol><p>The frequency of a scheduled report can be <strong>daily</strong>, <strong>weekly</strong> or <strong>monthly</strong>, and will be delivered to the user at 1 AM depending on the timezone specified.</p><p>We allow the user to specify exactly on which day he would like to receive the report — if it’s <strong>monthly</strong> or <strong>weekly</strong> by picking the day of delivery, if it’s daily — well you guessed it, it will be generated automatically every day.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*_aRaTS-AOE__p9NjWFKC_A.png" /><figcaption>schedule report creation through the control center</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*lK04wt4phtQl3MbRUS85Qw.png" /><figcaption>ad-hoc (on-demand) report creation through the control center</figcaption></figure><h4>SLOs — Service Level Objectives</h4><p><a href="https://sre.google/sre-book/service-level-objectives/">SLOs</a> are individual promises we make to a customer. SLOs are what set customer expectations and tell us what goals we need to achieve and what we need to measure ourselves against when providing a service.</p><h4>Reporting-API</h4><p>Reporting-API is the service in charge of generating ad-hoc and scheduled reports.</p><h4>Cronus</h4><p>Named after the Greek god of time ⌛ —This service is being used to create recurring schedules, such as scheduled reports.</p><h3>The issue</h3><p>We decided that our SLO for <strong>scheduled reports</strong> will be as such -</p><blockquote>99.9% of the scheduled reports will be generated at the expected time they were scheduled to, over a period of one month</blockquote><p><strong>How can we calculate such a thing?</strong></p><p>We had to separate this into two sub-tasks:</p><ol><li>Identifying how many scheduled reports have started in the previous hour</li><li>Identifying how many scheduled reports were expected to be generated in the previous hour</li></ol><p>By extracting this data, we will be able to determine if we “hit” our SLO with a simple calculation -</p><pre><strong>( 1 - ( absolute( SRS - SRE ) / SRE ) ) * 100</strong></pre><ul><li><strong>SRS</strong> — <strong>S</strong>cheduled <strong>R</strong>eports <strong>S</strong>tarted</li><li><strong>SRE</strong> — <strong>S</strong>cheduled <strong>R</strong>eports <strong>E</strong>xpected</li></ul><p>In other words, out of 100%, we will deduct the percentage of scheduled reports that were expected, but were not generated on time- which will give us the exact SLO we wanted, since now we received the complement result which is the number of scheduled reports that were generated at the expected time.</p><h3>Initial Metrics</h3><p>Our first step in calculating our target SLO, was to export common metrics of reports inReporting-API. By <strong>adding counter metrics</strong> using Prometheus at the <strong>beginning</strong> and <strong>end</strong> of report generation flows, we were able to measure how many ad-hoc/ scheduled reports <strong>started</strong> and in which status they finished.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/046d986236454052b492cf217b545c02/href">https://medium.com/media/046d986236454052b492cf217b545c02/href</a></iframe><p>In other words, every time we have an incoming request to create a report (ad-hoc/ scheduled) we raise the counter by one with the relevant identifiers.</p><p>Due to the counter metrics we implemented at the <strong>start</strong> of a report flow, we are now able to determine from incoming requests to Reporting-API, how many scheduled reports have started at a specific hour - which is the SRS parameter.</p><p>The following is an example of the Reporting-API metrics when querying the /metrics endpoint exposed by the Prometheus client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qdeVGYhEp89X2j_9RzHPnQ.png" /><figcaption>we care about <strong>reports_started_flow_counter</strong>’s that they’re <strong>is_scheduled</strong> equal to “1”, “0” means ad-hoc reports</figcaption></figure><p>In this example, we can see that there are 284 scheduled payment reports, and 224 scheduled settlement reports that have started in Reporting-API<strong> </strong>.</p><h3>Scheduled Reports Expected</h3><p>The next step was to measure SLOs specifically for our <strong>scheduled reports</strong>.</p><p>Identifying how many of our scheduled reports needed to be sent in the previous hour and comparing that to how many scheduled reports have actually started in the previous hour (in Reporting-API) was essential.</p><p>By doing that we could improve our system reliability, knowing exactly what happens to our scheduled reports and how many mismatches we have.</p><p>Let’s discuss how we’re going to calculate the SRE parameter.</p><h4>Wait, what?</h4><blockquote>Identifying how many scheduled reports were expected to be generated in the previous hour</blockquote><p><strong>How can we do that?</strong></p><p>The first thought we had was that we could get that information from Cronus itself since it already has all of the scheduled reports’ data.</p><p>On the other hand, we didn’t want the component in charge of sending the requests to generate a scheduled report to manage the expectations due to a few reasons:</p><ol><li>If a scheduled report request does not occur, what will happen? Cronus pulls out requests from a queue and sends them to a target service — what happens if a scheduled report request didn’t reach the queue,Cronus won’t be aware of it.</li><li>It’s not Cronus’ purpose to manage the scheduled reports’ expectations.</li></ol><p>Eventually, we decided to implement a separate service, whose sole purpose is to manage expectations of scheduled events (including reports) named SRMS<strong>.</strong></p><h3>SRMS — Scheduled Resources Monitoring Service</h3><p>The service’s main purpose is to export metrics once an hour, of what scheduled events were expected to occur based on events specifications in our system such as reports, and everything that is scheduled in our system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*94wm-QML_Xa31VvYLex9EA.png" /><figcaption>SRMS architecture</figcaption></figure><p>Let’s take a look at how SRMS is implemented. It has a dedicated topic which it consumes messages from and writes the data into its database.</p><p>Once an hour k8s cron-job triggers the SRMS via a dedicated endpoint — then it gathers all the scheduled events that were expected to occur in the previous hour in UTC (all schedule expressions are saved in UTC) by type and publishes the metrics by using Prometheus.</p><h4>How does the magic happen?</h4><p><a href="https://en.wikipedia.org/wiki/Cron#CRON_expression">Cron expression</a> holds a significant role in solving our issue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*QPwhnFRXZ4Zcy2JVkbGsZQ.png" /><figcaption>cron-expression supported format</figcaption></figure><p>By using a cron expression we can determine when a scheduled event needed to occur.</p><p>As we elaborated earlier, a scheduled report is sent at 1 AM depending on the timezone of the client and can be set as <strong>daily</strong>, <strong>weekly</strong>, or <strong>monthly</strong> — by using a cron expression we can describe exactly when a scheduled report is expected to be sent to the client.</p><blockquote>💡 When we save a scheduled event in SRMS database we save it in UTC</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*x5xQihVTwIy_8iYxcfdhjg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*8PefOx3z72_HviTH-NZ9NA.png" /><figcaption>weekly schedule on the left, and monthly schedule on the right</figcaption></figure><h4>SRMS topic: how does a message arrive?</h4><p>service-x publishes scheduled events messages to its topic.</p><p>An event in our case will be a scheduled report resource and its details, then a dedicated kafka-stream-x consumes from that topic and transforms the message to its desired form, and then publishes the new message to the SRMS topic.</p><p>A scheduled reports message, for example, is being mapped as such:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*zqMjSwAjx-WiRg-y4sCZdQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*cVA33hpEx-g3zkgltx04JQ.png" /><figcaption>The original message on the left is transformed into the message on the right which sent to the SRMS topic</figcaption></figure><p>How was this schedule_expression created?</p><p>Well, we know that all our reports are scheduled for 1 AM depending on the client’s timezone. We create a cron-expression corresponding to that time in UTC (while taking into consideration the time-zone offset) when the scheduled report needs to be sent.</p><p>In Africa/Abidjan the UTC offset is zero, therefore we don’t need to align the time from 1 AM, so it stays 1 AM. This is a daily scheduled report so eventually, we get 0 1 * * *— “At 01:00” (Every day).</p><blockquote><em>💡</em> The TTL of a scheduled resource will also be calculated if a message contains an end_date field</blockquote><h4>How does SRMS look with an integrated service that uses it?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wt0_RFkgkDtSj057hXqYXQ.png" /><figcaption>SRMS with an integrated service-x</figcaption></figure><blockquote><em>💡 </em>service-<strong>x</strong> can be considered as Reporting-API</blockquote><p>As we said service-x receives a create/ delete scheduled resource request, then it publishes a Kafka message to its events topic, that message is then consumed by service-x-kafka-stream that parse the message and produce it back into the srms-topic, and then SRMS service does its magic.</p><h3>The SRMS metrics — Expectations</h3><p>Like we described earlier, when the SRMS is being triggered by the k8s cron-job we parse each record and decide if it was supposed to occur in the previous hour by its schedule expression, this can be done by using an npm package named cron-parser which helps us to extract the previous timestamp a record needed to occur.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d9eae6ecff1ec03c5c3d92576cfdc12/href">https://medium.com/media/7d9eae6ecff1ec03c5c3d92576cfdc12/href</a></iframe><p>After we extracted the timestamp of the last time a record was supposed to be triggered, we can now determine if we need to include it as part of the expectations results or not.</p><p>Now that we have all the records that were supposed to be triggered by Cronus in the previous hour, we group and count them by resource type, and label, and export the metrics to Prometheus.</p><p>Eventually, we will receive a response as such:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/745052fc5afa43da90c817b0c621bfd3/href">https://medium.com/media/745052fc5afa43da90c817b0c621bfd3/href</a></iframe><p>This means there are 14 settlement reports and 9 payment reports that were supposed to be triggered in the previous hour. In total for scheduled reports, the SRE (Scheduled Reported Expected) parameter equals 23.</p><p>The only thing left is to compare those results with how many scheduled reports have started in Reporting-API (SRS - <strong>S</strong>cheduled <strong>R</strong>eported <strong>S</strong>tarted).</p><h3>Putting the pieces together</h3><p>We managed to identify <strong><em>how many of our scheduled reports were expected to be sent in the previous hour (SRE)</em></strong>, and we know<strong><em> how many scheduled reports have started in the previous hour (SRS)</em></strong>, now we will combine the results using a query to run in Grafana(The query goes to Thanos).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nNbxiU52dDpN5eI49y1Isw.png" /><figcaption>The query we used in Grafana (PromQL)</figcaption></figure><blockquote><em>💡</em> We decided that our source of truth will be the SRMS expectations (<strong>SRE</strong>) which is why we divide the absolute diff by the <em>SRMS</em> expectations</blockquote><p>The query on top gave us the following graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*lfem4O5ud-H0tjCod2rslQ.png" /><figcaption>In this graph, we can see that during the last day/ week 100% of our scheduled reports were sent on time to our clients</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*pAHtDFIHM1Lv39Zb1KJgWw.png" /><figcaption>If we dive into reports, we will see that 44/44 scheduled reports were created as expected during the last day — while 1/1 were sent as expected in the last hour</figcaption></figure><p>The next step was to implement alerts, so every time the following equation result will be below 99.9%, we will receive an alert in our slack channel.</p><pre><strong>( 1 - ( absolute( SRS - SRE ) / SRE ) ) * 100 &lt; 99.9</strong></pre><p>That’s basically it, it took time and effort, but eventually, we managed to gather solid and stable data and created alerts based on it.</p><p>After one month of monitoring the data, we saw that the SLO we defined for scheduled reports was solid and at the time of writing this blog, 100% of our scheduled reports were sent right on time, and if for some reason in the future it will go under 99.9% we’ll be sure to know about it.</p><h3>Conclusion</h3><p>A couple of things that I would like you to take away from this post:</p><ol><li>The process of monitoring scheduled events can be complex and time-consuming, and the data may differ at the end of the journey due to metrics time windows, and the way Prometheus query language works (PromQL) when querying the data.</li><li>Working with timezones and DST (Daylight Saving Time) is a living nightmare 💀 — We had many bugs due to timezone calculations when generating the cron expression for the scheduled reports. One of the packages that saved our life was date-fns-tz, which enabled us to extract the UTC offset of the timezone <strong>with DST</strong> a few years back by using a timestamp!</li><li>When it comes to metrics for scheduled events we need 100% accuracy. Therefore, Prometheus is not the right tool for the job. If I had to choose a different technology, ElasticSearch would be my choice - it’s fast and enables us to query the data in almost every way we desire without limitations so our data would be accurate, if we had used it we could have queried the metrics by the exact time window we wanted, which could help us solve adjustments issues we had when trying to find the “sweet spot” of when to send the query to Thanos for extracting metrics from Reporting-API.</li></ol><p>So there we have it! Hopefully, now you’ll have the tools to monitor your own scheduled events ✌️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91930e6992e6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/payu-engineering/how-we-managed-to-monitor-scheduled-events-in-our-system-91930e6992e6">How we managed to monitor scheduled events in our system</a> was originally published in <a href="https://medium.com/payu-engineering">payu-engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>