<?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 Shashank Tyagi on Medium]]></title>
        <description><![CDATA[Stories by Shashank Tyagi on Medium]]></description>
        <link>https://medium.com/@tyagishashank118?source=rss-b35e56aa4b3d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*KijM702cjRcE5GkM</url>
            <title>Stories by Shashank Tyagi on Medium</title>
            <link>https://medium.com/@tyagishashank118?source=rss-b35e56aa4b3d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 14:18:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tyagishashank118/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[Event-driven architecture : The Outbox Pattern]]></title>
            <link>https://medium.com/@tyagishashank118/event-driven-architecture-the-outbox-pattern-eb0e8b817f14?source=rss-b35e56aa4b3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb0e8b817f14</guid>
            <category><![CDATA[atomic-transaction]]></category>
            <category><![CDATA[outbox-pattern]]></category>
            <category><![CDATA[event-driven-systems]]></category>
            <category><![CDATA[audit-logging]]></category>
            <dc:creator><![CDATA[Shashank Tyagi]]></dc:creator>
            <pubDate>Fri, 24 Apr 2026 17:34:51 GMT</pubDate>
            <atom:updated>2026-04-24T17:51:32.846Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How production systems guarantee that important events never quietly disappear — even when things crash at the worst possible moment.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u_4THVJat4EU_JAWaIW4IQ.png" /></figure><p>A few weeks into my current job, I was reading through a service that creates user records. I expected to see the usual: write to the database, publish an event to Kafka, done.</p><p>Instead, I found something unexpected. After writing the user record, the code was also inserting a row into a second table — user_created_outbox. Both writes happened inside the same database transaction. Then there was a completely separate process, somewhere else in the system, that read from that outbox table and forwarded events downstream.</p><p>I had stumbled onto the <strong>Transactional Outbox Pattern</strong>. Once I understood why it exists, I couldn’t unsee it everywhere.</p><h3>The Problem It Solves</h3><p>Imagine you’re building a service that handles user signups. When someone signs up, two things need to happen:</p><p><strong>Write to the database: </strong>Create the user record — name, email, timestamps.</p><p><strong>Publish to the message queue: </strong>Emit a user.created event so other services can react — send a welcome email, provision storage, update a leaderboard, whatever.</p><p>The naive implementation looks like this:</p><pre>// Naive approach — looks fine, hides a bug<br>func CreateUser(ctx context.Context, user User) error {<br>    if err := db.Insert(ctx, user); err != nil {<br>        return err<br>    }</pre><pre>    // What if the process crashes right here?</pre><pre>    event := UserCreatedEvent{UserId: user.Id, Email: user.Email}<br>    return kafka.Publish(ctx, &quot;user.created&quot;, event)<br>}</pre><p><strong>The hidden failure mode:</strong><em> Your process crashes, runs out of memory, or loses its network connection in the gap between the DB write and the Kafka publish. The user is now in the database — but the event never went out. Downstream services have no idea this user exists.</em></p><p>This isn’t theoretical. In a high-traffic system, <em>something</em> is always crashing or timing out. The question is whether your architecture survives it.</p><p>DB write succeeds, event lostEvent published twice on retryNo visibility into what failed</p><p>You can’t solve this with a transaction across two different systems — databases and message queues don’t share a transaction boundary. That’s the fundamental constraint. The outbox pattern is how you work around it.</p><h3>The Core Idea</h3><blockquote>“Write the event to the same database, in the same transaction. Let a separate process forward it.”</blockquote><p>Instead of publishing to Kafka directly from application code, you write the event into a special table — the <strong>outbox table</strong> — in the same atomic transaction as your main write. A separate relay process then reads from this table and forwards events onward.</p><p>The key insight: if the transaction commits, the event row is there. If the transaction rolls back, the event row is gone too. They’re always in sync — because they’re the same operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RuELPHzRav7S-pQBcTRTaA.png" /><figcaption>claude generated</figcaption></figure><h3>But wait — why not just watch the original table?</h3><p>This is a fair question. If you want to know when a new user signs up, why not just query the users table directly? Poll for rows where created_at &gt; last_checked. Simple. No extra table, no extra complexity.</p><p>The problem is that your domain table only tells you <em>state</em>. It shows you what exists right now. It says nothing about what <em>happened</em>.</p><p>Picture this: a user signs up, then immediately updates their email before your polling service runs. You poll, you see the user — but was this a “user created” event or a “user updated” event? You can’t tell. The table just shows you the current row. The moment of creation has already been overwritten.</p><blockquote>“The domain table tracks what is. The outbox table tracks what happened.”</blockquote><p>That distinction matters more as the system grows. A single user creation might need to trigger several downstream reactions — start a trial, initialize onboarding, send a welcome email. Those are three separate events with potentially different payloads and different consumers. There’s no clean way to represent that in the users table without polluting it with columns that have nothing to do with a user.</p><p>And then there are the edge cases that polling domain tables genuinely can’t handle. If a row gets deleted, it’s gone — but the user.deleted event still needs to go out. If the same table is written to by ten different code paths — signups, admin imports, data migrations — your polling logic has to figure out <em>why</em> a row appeared, which quickly turns into a mess of heuristics. And if different consumers need different shapes of the same event, you&#39;d have to bake all of that into one overloaded table.</p><p><strong>The deeper issue:</strong><em> your domain table is optimized for querying current state — fast lookups, clean indexes, normalized data. The moment you start using it as an event log, you’re fighting its design. You end up adding columns like </em><em>processed, </em><em>last_polled_at, </em><em>event_version that have nothing to do with the domain. The outbox table exists so your domain table doesn&#39;t have to be something it isn&#39;t.</em></p><h3>What the Outbox Table Looks Like</h3><p>The outbox table isn’t special infrastructure. It’s a plain database table that lives right next to your domain tables — in the same database, under the same schema. What makes it distinct is <em>purpose</em>: it’s a staging area. Events land here on their way out of the system, and the relay process drains it.</p><p>Each row represents one event. It holds who triggered it (company_id, tenant_id), what happened (type), when it happened (time), and the full payload as a JSON blob (data). There&#39;s also a source field that acts as a compound routing key — encoding the domain, environment, event type, and version into a single string. Consumers use that to decide whether a given event is relevant to them.</p><p>The schema_version column deserves its own mention. Tables get versioned — user_created_outbox_v1, user_created_outbox_v2 — and when a schema changes, you create a new versioned table rather than modifying the old one. This means consumers can keep reading from v1 while you migrate them to v2 at their own pace. No coordinated deployment. No big-bang cutover. Each consumer upgrades independently.</p><h3>Three Ways to Write to the Outbox</h3><p>The write side isn’t always identical. In practice, there are at least three patterns you’ll encounter:</p><h3>Pattern 1 — Same atomic call</h3><p>The most common approach: include both the domain write and the outbox insert in a single transaction. In Go, this might look like:</p><pre>// Both rows go into the same Modify() call — one atomic transaction<br>err := db.Modify(<br>    ctx,<br>    createRequests: [outboxRow, domainRow],<br>    updateRequests: [],<br>    deleteRequests: [],<br>    tenantId,<br>)<br>// Either both succeed, or neither does. No in-between.</pre><h3>Pattern 2 — Builder helper</h3><p>Some codebases have a helper that constructs outbox rows from a slice of event objects, so the calling code just passes events and the infrastructure handles table routing:</p><pre>events := []BusinessEvent{userCreatedEvent, profileInitializedEvent}<br>outboxRows, _ := GetModifyRowsRequestForBusinessEvents(ctx, events, idGen)</pre><pre>db.Modify(ctx, append(domainRows, outboxRows...), ...)<br>// Segregates by event type, derives table name automatically</pre><h3>Pattern 3 — Database trigger</h3><p>For legacy tables or write-heavy paths, some teams use MySQL AFTER INSERT triggers. The application code writes to the main table; the DB engine automatically inserts the outbox row:</p><pre>CREATE TRIGGER after_users_created<br>    AFTER INSERT ON users FOR EACH ROW<br>BEGIN<br>    INSERT INTO user_created_outbox_v1 (company_id, tenant_id, data, type, ...)<br>    VALUES (NEW.company_id, NEW.tenant_id, JSON_OBJECT(&#39;user_id&#39;, NEW.id, ...), ...);<br>END</pre><p>This is the “zero app-layer changes” variant — the trigger fires on every insert regardless of what wrote the row. Useful when you’re adding observability to an existing table without modifying every write path.</p><h3>How Events Get Forwarded</h3><p>The outbox table is just storage. Something still needs to read from it and forward events. There are two main approaches:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XUYGk_HB7gz6CyGdPvC2Fg.png" /></figure><p><strong>Change Data Capture (CDC)</strong> is the more production-grade approach. Tools like Debezium tail the database’s binary log — the same mechanism used for replication — and emit an event whenever a row is inserted into the outbox table. No polling. Near-realtime. No additional load on the database beyond the replication stream it was already producing.</p><p><strong>Polling</strong> is simpler to stand up: a background thread periodically queries the outbox table for unprocessed rows, publishes them, and marks them as done. Fine for lower-volume systems, but the polling interval introduces latency, and at high insert rates it creates contention.</p><h3>Idempotency — The Other Half of the Puzzle</h3><p>The outbox pattern gives you <em>at-least-once</em> delivery, not <em>exactly-once</em>. The relay process might crash after publishing an event but before marking it as processed — so it will publish the same event again on restart.</p><p>This means consumers must be idempotent. Receiving the same event twice should produce the same outcome as receiving it once. Common approaches:</p><p><strong>Deduplicate by event ID: </strong>Each outbox row has a unique ID. Consumers track which IDs they’ve already processed and skip duplicates.</p><p><strong>Upsert instead of insert: </strong>Design your writes so that inserting the same record twice is the same as inserting it once. Natural idempotency.</p><p><strong>Ignore AlreadyExists errors: </strong>Some systems silently skip events that produce a unique-constraint violation on the downstream side — a lightweight and effective approach.</p><p><strong>Key principle:</strong><em> The relay process can be retried safely as many times as needed. Idempotent consumers mean retries are harmless. This combination — at-least-once delivery with idempotent processing — is how you get effectively-exactly-once semantics without distributed transactions.</em></p><h3>Why This Beats the Alternatives</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lpDxtql6hBy7DyJP9TvRDg.png" /></figure><h3>When Should You Use This?</h3><p>The outbox pattern makes sense whenever you have a domain write that <em>must</em> trigger a downstream reaction and you can’t afford silent failures. Some concrete use cases:</p><p>user signup → send welcome emailorder placed → notify fulfillmentpayment confirmed → unlock featurecontent published → fan-out to subscribersrecord updated → sync to search index</p><p>It’s <em>not</em> the right choice when events are fire-and-forget with no consistency requirement — if losing an analytics ping occasionally is fine, the complexity isn’t worth it. The pattern adds operational surface area: you need to monitor the outbox table for stuck rows, manage schema versions, and ensure your relay process stays healthy.</p><h3>What I Took Away</h3><p>What struck me most when I first saw this pattern was how simple the core idea is. You don’t need a distributed transaction. You don’t need special infrastructure at the write path. You just need to write your events to the same database that already stores your domain data — and let a separate process deal with forwarding.</p><p>The constraint it works around — that you can’t atomically span a database and a message queue — isn’t solved. It’s sidestepped. The event relay becomes the bridge, and the outbox table becomes the buffer that survives crashes.</p><p>Once you’ve seen it in a production codebase, the naive “write to DB, then publish” pattern starts to look fragile. Because it is.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb0e8b817f14" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real-Time Change Data Capture with Debezium and PostgreSQL]]></title>
            <link>https://medium.com/@tyagishashank118/real-time-change-data-capture-with-debezium-and-postgresql-50f3db656ca5?source=rss-b35e56aa4b3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/50f3db656ca5</guid>
            <category><![CDATA[change-data-capture]]></category>
            <category><![CDATA[debezium]]></category>
            <category><![CDATA[real-time-streaming-data]]></category>
            <category><![CDATA[kafka-connect]]></category>
            <category><![CDATA[debezium-kafka-kubernetes]]></category>
            <dc:creator><![CDATA[Shashank Tyagi]]></dc:creator>
            <pubDate>Wed, 08 Oct 2025 16:14:29 GMT</pubDate>
            <atom:updated>2025-10-08T16:14:29.783Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Bks7umIkKiQhYXrL.png" /></figure><h3>The Problem</h3><p>Imagine this: You have a system where every time something changes in your database, another part of your system needs to know. Maybe it’s a billing service that needs to react when a new order is created, or a notification system that sends alerts when a user updates their profile.</p><p>How do you keep everything in sync in real-time?</p><p>The naive approach is simple: whenever something changes, query the database, pull together the data you need, and publish an event for downstream services. This works until it doesn’t.</p><p>What happens when the event isn’t just a single field? What if your schema evolves, or ten different services depend on consistent, real-time updates? Suddenly, your “quick fix” becomes a maintenance nightmare of custom code, brittle queries, and missed updates.</p><p><strong>This is where Change Data Capture (CDC) comes in.</strong></p><h3>What is Change Data Capture?</h3><p>Instead of writing fragile glue code to detect changes, CDC automatically streams every change from your database into Kafka in real-time with full context, schema, and history.</p><p>Think of it this way: Your database becomes a broadcaster. Every insert, update, and delete is an event that gets published automatically. You don’t poll for changes — the database itself becomes a producer of events.</p><p>The magic? You get this without changing a single line of your application code. No triggers, no custom queries, no forgotten edge cases.</p><h3>When You Need CDC</h3><p>CDC solves these critical problems in modern data architectures:</p><p><strong>1. Real-Time Analytics</strong><br> Stream changes directly to your data warehouse or analytics platform. No more stale dashboards or overnight batch jobs. your analytics are always current.</p><p><strong>2. Read Optimization (CQRS)</strong><br> Your production database is optimized for writes, but reads are slow. CDC lets you stream data to read-optimized stores (Elasticsearch, data warehouses, Redis) without dual writes or complex synchronization logic.</p><p><strong>3. Cache Consistency </strong><br> Keep Redis or other caches perfectly synchronized with your source database. No more stale cache data or manual invalidation logic.</p><p><strong>4. Avoiding Dual Writes</strong><br> Writing to multiple databases simultaneously is error-prone. One write succeeds, the other fails, now what? With CDC, write to your primary database and let the CDC pipeline update secondary systems asynchronously.</p><p><strong>5. Microservices Communication</strong><br> Maintain eventual consistency between microservice databases without tight coupling or heavy inter-service API calls. Each service reads the changes it cares about from the stream.</p><h3>See It Working in 5 Minutes</h3><p>Before we dive into architecture details, let’s see CDC in action. This proves the value immediately.</p><h3>PostgreSQL Configuration</h3><p>The most critical requirement is enabling logical replication. This requires modifying postgresql.conf and restarting PostgreSQL.</p><p><strong>Required Settings:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gej2mEN54iGREpM4eUBW3w.png" /></figure><p><strong>Edit your </strong><strong>postgresql.conf:</strong></p><pre>wal_level = logical<br>max_wal_senders = 10<br>max_replication_slots = 10<br>max_worker_processes = 16</pre><p><strong>Restart PostgreSQL:</strong></p><pre>sudo systemctl restart postgresql</pre><p>If you are using RDS or any clound managed postgres, you won’t have direct access to postgresql.conf , instead edit these settings in parameter groups.</p><h3>Database User Permissions</h3><p>The Debezium connector needs a user with replication privileges:</p><pre>-- Create a dedicated user for Debezium<br>CREATE USER debezium_user WITH REPLICATION PASSWORD &#39;secure_password&#39;;</pre><pre>-- Grant necessary permissions<br>GRANT CONNECT ON DATABASE demo TO debezium_user;<br>GRANT USAGE ON SCHEMA public TO debezium_user;<br>GRANT SELECT ON ALL TABLES IN SCHEMA public TO debezium_user;</pre><pre>-- Grant permissions for future tables<br>ALTER DEFAULT PRIVILEGES IN SCHEMA public <br>  GRANT SELECT ON TABLES TO debezium_user;</pre><p>Want a ready-to-run setup? Check out this repository with Kafka, and Debezium pre-configured:</p><p>It comes with <strong>Kafka (running in KRaft mode)</strong>, <strong>Schema Registry</strong>, <strong>Debezium Connect</strong>, and <strong>Kafka UI</strong> pre-configured.</p><p><a href="https://github.com/LEVIII007/debezium-kafka-setup">GitHub - LEVIII007/debezium-kafka-setup</a></p><h3>Step 1: Start the Stack</h3><p>Clone the repository and run:</p><pre>docker compose up -d</pre><p>This will start:</p><ol><li><strong>Three Kafka brokers</strong> (running in KRaft mode, no Zookeeper required).<br> Each broker runs on ports 9092, 9093, and 9094.</li><li><strong>Schema Registry</strong> on port 8081, to manage Avro schemas and message compatibility.</li><li><strong>Kafka Connect</strong> (with Debezium pre-installed) on port 8083.<br> This is where you’ll register the PostgreSQL connector later.</li><li><strong>Kafka UI</strong> on port 8080, giving you a friendly web interface to explore topics and connector states.</li></ol><p>Once the containers are up, you can open the UI in your browser at:</p><p>👉 <a href="http://localhost:8080/"><strong>http://localhost:8080</strong></a></p><h3>Step 2: Create a Sample Table</h3><p>Connect to PostgreSQL and create an orders table:</p><pre>CREATE TABLE orders (<br>    id SERIAL PRIMARY KEY,<br>    customer_name VARCHAR(100),<br>    product VARCHAR(100),<br>    amount NUMERIC,<br>    status VARCHAR(20),<br>    created_at TIMESTAMP DEFAULT NOW()<br>);</pre><h3><strong>Step 3: Configure the Debezium Connector</strong></h3><p>Create a file called register-postgres.json:</p><pre>{<br>  &quot;name&quot;: &quot;orders-connector&quot;,<br>  &quot;config&quot;: {<br>    &quot;connector.class&quot;: &quot;io.debezium.connector.postgresql.PostgresConnector&quot;,<br>    &quot;tasks.max&quot;: &quot;1&quot;,<br>    &quot;database.hostname&quot;: &quot;postgres&quot;,<br>    &quot;database.port&quot;: &quot;5432&quot;,<br>    &quot;database.user&quot;: &quot;postgres&quot;,<br>    &quot;database.password&quot;: &quot;password&quot;,<br>    &quot;database.dbname&quot;: &quot;demo&quot;,<br>    &quot;topic.prefix&quot;: &quot;dbserver1&quot;,<br>    &quot;plugin.name&quot;: &quot;pgoutput&quot;,<br>    &quot;slot.name&quot;: &quot;orders_slot&quot;,<br>    &quot;publication.name&quot;: &quot;orders_pub&quot;,<br>    &quot;table.include.list&quot;: &quot;public.orders&quot;,<br>    &quot;snapshot.mode&quot;: &quot;initial&quot;<br>  }<br>}</pre><p><strong>What does this configuration do?</strong></p><ul><li>topic.prefix: Sets the base name for Kafka topics (results in dbserver1.public.orders)</li><li>plugin.name: Uses pgoutput (native PostgreSQL logical replication)</li><li>slot.name / publication.name: PostgreSQL mechanisms Debezium uses under the hood</li><li>table.include.list: Only watch the orders table</li><li>snapshot.mode: Start with a full snapshot of existing data, then stream changes</li></ul><p>These are not the only configurations available, you can do much more. See this <a href="https://debezium.io/documentation/reference/stable/connectors/mysql.html#mysql-connector-properties">doc</a></p><p>Register the connector with Kafka Connect:</p><pre>curl -X POST http://localhost:8083/connectors \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d @register-postgres.json</pre><h3>Step 4: Watch the Magic Happen</h3><p>Insert a record into your orders table:</p><pre>INSERT INTO orders (customer_name, product, amount, status)<br>VALUES (&#39;John Doe&#39;, &#39;Laptop&#39;, 1200.00, &#39;pending&#39;);</pre><p>Now consume from the Kafka topic:</p><pre>docker exec -it kafka kafka-console-consumer \<br>  --bootstrap-server localhost:9092 \<br>  --topic dbserver1.public.orders \<br>  --from-beginning</pre><p>You’ll see a JSON event that looks like this:</p><pre>{<br>  &quot;before&quot;: null,<br>  &quot;after&quot;: {<br>    &quot;id&quot;: 1,<br>    &quot;customer_name&quot;: &quot;John Doe&quot;,<br>    &quot;product&quot;: &quot;Laptop&quot;,<br>    &quot;amount&quot;: 1200.00,<br>    &quot;status&quot;: &quot;pending&quot;,<br>    &quot;created_at&quot;: 1704672000000<br>  },<br>  &quot;source&quot;: {<br>    &quot;version&quot;: &quot;2.1.0.Final&quot;,<br>    &quot;connector&quot;: &quot;postgresql&quot;,<br>    &quot;name&quot;: &quot;dbserver1&quot;,<br>    &quot;ts_ms&quot;: 1704672000123,<br>    &quot;db&quot;: &quot;demo&quot;,<br>    &quot;schema&quot;: &quot;public&quot;,<br>    &quot;table&quot;: &quot;orders&quot;<br>  },<br>  &quot;op&quot;: &quot;c&quot;,<br>  &quot;ts_ms&quot;: 1704672000456<br>}</pre><p><strong>That’s it!</strong> Every change in your database is now streaming to Kafka in real-time. Update a row, delete a row :- all of it flows through automatically.</p><p><strong>If you only came here to get the setup running</strong>, you can stop right here. Everything beyond this point dives deeper into theory.</p><h3>How Debezium Works Under the Hood</h3><p>Now that you’ve seen CDC in action, let’s understand what’s happening behind the scenes.</p><h3>The Architecture</h3><p>A production-grade CDC pipeline has five layers working together:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XrcBCPdcrRPmJfiKrVMCCw.png" /><figcaption>source : <a href="https://debezium.io/documentation/reference/stable/architecture.html">https://debezium.io/documentation</a></figcaption></figure><p><strong>How It Works Step-by-Step</strong></p><ol><li><strong>PostgreSQL Writes to the WAL (Write-Ahead Log)</strong><br> Every change in PostgreSQL is first written to the WAL before being applied to the actual data files. This is standard PostgreSQL behavior for crash recovery.</li></ol><p><strong>2. Logical Decoding Reads the WAL</strong><br> When you set wal_level=logical, PostgreSQL can decode these WAL entries into a structured format that external tools can understand. This decoded stream contains information about what changed, which table, and the before/after values.</p><p><strong>3. Replication Slot Maintains Position</strong><br> A replication slot is like a bookmark. It tells PostgreSQL: “Don’t delete WAL segments until this consumer (Debezium) has processed them.” This ensures no changes are lost.</p><p><strong>4. Debezium Connector Consumes and Transforms</strong><br> The Debezium PostgreSQL connector connects to the replication slot, reads the decoded changes, and transforms them into standardized event messages with rich metadata (timestamps, schema info, transaction boundaries).</p><p><strong>5. Kafka Connect Manages Everything</strong><br> Kafka Connect is the framework that runs the Debezium connector. It handles restarts, scaling, configuration updates via REST API, and ensures exactly-once delivery semantics.</p><p><strong>6. Events Land in Kafka Topics</strong><br> Each table gets its own Kafka topic following a naming convention: {topic.prefix}.{schema}.{table}. For example: dbserver1.public.orders.</p><h3>Why Debezium Over other Solutions?</h3><p><strong>Approach 1 : </strong>Native Postgres CDC with wal2json</p><p>You <em>could</em> build CDC yourself using PostgreSQL’s native logical replication and the wal2json plugin in your code. Here&#39;s what that looks like:</p><pre>// Connect directly to Postgres replication protocol<br>conn, _ := pgconn.Connect(ctx, &quot;connection_string&quot;)<br>conn.RuntimeParams[&quot;replication&quot;] = &quot;database&quot;// Create a replication slot<br>slotName := &quot;custom_slot&quot;<br>conn.Exec(ctx, fmt.Sprintf(<br>  &quot;SELECT * FROM pg_create_logical_replication_slot(&#39;%s&#39;,&#39;wal2json&#39;)&quot;, <br>  slotName<br>))// Start consuming WAL changes<br>pglogrepl.StartReplication(ctx, conn, slotName, 0, ...)// Process each change manually<br>for {<br>    msg, _ := conn.ReceiveMessage(ctx)<br>    // Parse JSON, handle schema changes, manage offsets...<br>}</pre><p>full code <a href="https://github.com/LEVIII007/debezium-kafka-setup/blob/main/diy-cdc.go">here</a>.</p><p>This works for prototypes, but in production you’ll need to handle:</p><ul><li>Schema evolution (what happens when columns are added/removed?)</li><li>Exactly-once delivery semantics</li><li>Connector restarts and state management</li><li>Monitoring and alerting</li><li>Backpressure handling</li><li>Multiple table coordination</li></ul><p><strong>Debezium gives you all of this out of the box</strong>, along with:</p><ul><li><strong>Snapshot functionality</strong>: Capture existing data when starting</li><li><strong>Filtering</strong>: Include/exclude specific tables or columns</li><li><strong>Data masking</strong>: Protect sensitive fields (e.g., mask credit card numbers)</li><li><strong>Message transformations</strong>: Flatten payloads, route to different topics</li><li><strong>Production-tested reliability</strong>: Used by thousands of companies at scale</li></ul><p>What would be the really bad way to Implement CDC?</p><p>Before we look at the right solution, let’s understand why the common approaches fail at scale.</p><h3>Approach 2: Polling (Pull-Based CDC)</h3><p>The most common “solution” developers reach for:</p><pre>-- Run this every few seconds<br>SELECT * FROM orders <br>WHERE updated_at &gt; :last_check_timestamp<br>ORDER BY updated_at;</pre><p><strong>The idea:</strong> Periodically query for rows that changed since your last check.</p><h3>Approach 2: Database Triggers (Push-Based CDC)</h3><p>A step up from polling — use database triggers to automatically push changes:</p><pre>CREATE OR REPLACE FUNCTION notify_order_change()<br>RETURNS TRIGGER AS $<br>BEGIN<br>  PERFORM pg_notify(&#39;order_changes&#39;, <br>    json_build_object(<br>      &#39;id&#39;, NEW.id,<br>      &#39;action&#39;, TG_OP,<br>      &#39;data&#39;, row_to_json(NEW)<br>    )::text<br>  );<br>  RETURN NEW;<br>END;<br>$ LANGUAGE plpgsql;</pre><pre>CREATE TRIGGER order_change_trigger<br>AFTER INSERT OR UPDATE OR DELETE ON orders<br>FOR EACH ROW EXECUTE FUNCTION notify_order_change();</pre><p><strong>The idea:</strong> Let the database tell you when something changes instead of asking.</p><p>If i have to tell you in very less words why last 2 methods are really bad: <strong>Extra work for database</strong></p><h3>Advanced Connector Configuration</h3><p>By default, Debezium sends verbose messages with before, after, source, and metadata. If your consumers only need the final state, apply the ExtractNewRecordState transformation:</p><p><strong>Before transformation:</strong></p><pre>{<br>  &quot;before&quot;: null,<br>  &quot;after&quot;: {<br>    &quot;id&quot;: 1,<br>    &quot;customer_name&quot;: &quot;John Doe&quot;,<br>    &quot;amount&quot;: 1200.00<br>  },<br>  &quot;source&quot;: { /* metadata */ },<br>  &quot;op&quot;: &quot;c&quot;<br>}</pre><p><strong>After transformation (unwrapped):</strong></p><pre>{<br>  &quot;id&quot;: 1,<br>  &quot;customer_name&quot;: &quot;John Doe&quot;,<br>  &quot;amount&quot;: 1200.00<br>}</pre><p>This makes consumption simpler for downstream services that don’t need CDC-specific metadata.</p><h3>Monitoring and Operations</h3><h3>Check Connector Status</h3><pre>curl http://localhost:8083/connectors/orders-connector/status | jq</pre><h3>View Active Replication Slots</h3><pre>SELECT slot_name, active, restart_lsn, confirmed_flush_lsn <br>FROM pg_replication_slots;</pre><h3>Monitor Replication Lag</h3><pre>SELECT <br>  slot_name,<br>  pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS lag<br>FROM pg_replication_slots;</pre><p>If lag grows too large, check:</p><ul><li>Is Kafka Connect running?</li><li>Is the connector paused or failed?</li></ul><h3><strong>Cleaning Up</strong></h3><p>To stop CDC and remove the replication slot:</p><pre># Delete the connector<br>curl -X DELETE http://localhost:8083/connectors/orders-connector</pre><pre># Drop the replication slot in PostgreSQL<br>SELECT pg_drop_replication_slot(&#39;orders_slot&#39;);</pre><p><strong>Warning:</strong> Don’t drop replication slots while the connector is running — this will cause data loss.</p><h3>Conclusion</h3><p>You’ve just built a production-grade CDC pipeline. Every insert, update, or delete in your PostgreSQL database now streams into Kafka in real-time automatically, reliably, and without custom code.</p><p>The beauty of CDC is that once it’s running, it’s invisible. Your applications write to the database as usual and everything else just stays synchronized automatically.</p><p><strong>Resources :</strong></p><ul><li><a href="https://debezium.io/documentation/">Debezium Documentation</a></li><li><a href="https://www.postgresql.org/docs/current/logical-replication.html">PostgreSQL Logical Replication</a></li><li><a href="https://github.com/LEVIII007/debezium-kafka-setup">Sample Setup Repository</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50f3db656ca5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monitoring Microservices on a Budget: Our Journey with SigNoz]]></title>
            <link>https://medium.com/@tyagishashank118/monitoring-microservices-on-a-budget-our-journey-with-signoz-9b16ce02f778?source=rss-b35e56aa4b3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b16ce02f778</guid>
            <category><![CDATA[opentelemetry-collector]]></category>
            <category><![CDATA[signoz]]></category>
            <category><![CDATA[opentelemetry]]></category>
            <category><![CDATA[logging-and-monitoring]]></category>
            <category><![CDATA[alternatives-to-datadog]]></category>
            <dc:creator><![CDATA[Shashank Tyagi]]></dc:creator>
            <pubDate>Fri, 19 Sep 2025 11:00:58 GMT</pubDate>
            <atom:updated>2025-09-19T11:00:58.429Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VxdMK7az8qVA1hwgYZCXxw.png" /></figure><p>After losing 3–4 hours twice just figuring out where the issue was, we realized we needed <strong>proper observability</strong>.</p><p>At that time, we only had a very barebones OpenTelemetry setup — no alerts, no dashboards, just raw logs for the past few hours. If we needed to go back a bit further, it meant SSHing into a machine and grepping through Docker logs. Painful. Slow. And definitely not scalable.</p><p>That’s when we decided to set up <strong>SigNoz</strong>. Not just as a temporary fix, but as a <strong>full-stack observability platform</strong>:</p><ul><li>Dashboards for real-time visibility</li><li>Alerts so we don’t discover issues hours later</li><li>Traces, metrics, and logs all in one place</li></ul><p>And honestly, a lot more features I haven’t even fully explored yet</p><p>The best part? It’s open-source, self-hosted, and runs on a single machine if you want it to.</p><h3>Why This Guide?</h3><p>You can spin up SigNoz quickly by cloning their repo and running docker-compose up. But in real life, almost nobody wants a vanilla setup. You’ll want to <strong>customize configs</strong>, maybe reverse-proxy it behind Nginx, tweak storage, or override defaults.</p><p>That’s why I prefer a <strong>setup-as-code</strong> approach — something you can replicate anywhere in just a few minutes, modify easily, and commit to version control.</p><p>Here’s what my current repo looks like:</p><pre>├── Makefile<br>├── nginx<br>│   ├── conf.d<br>│   │   └── default.conf<br>│   └── docker-compose.yml<br>├── README.md<br>├── scripts<br>│   └── bootstrap_signoz.sh<br>├── signoz-override<br>│   └── docker-compose.override.yml<br>└── clickhouse<br>    ├── config.d<br>    │   └── z_custom_settings.xml<br>    └── users.d<br>        └── z_users.xml</pre><h3>Let’s first see Signoz Stack :</h3><h3>Quick mental model (3 planes)</h3><ul><li><strong>Ingest Plane</strong> → Your apps + agents send data (OTLP) to the <strong>OpenTelemetry Collector</strong>.</li><li><strong>Storage Plane</strong> → The Collector writes normalized data into <strong>ClickHouse</strong> (fast columnar OLAP DB).</li><li><strong>Query &amp; UX Plane</strong> → SigNoz <strong>Query Service</strong> + <strong>UI</strong> read from ClickHouse; <strong>Alertmanager</strong> fires notifications.</li></ul><h3>Core components (what each one does):</h3><p><strong>OpenTelemetry Collector:</strong> front door for all telemetry. Your apps send OTLP (gRPC/HTTP) here; the collector batches/enriches it and writes traces/metrics/logs to storage.</p><p><strong>ClickHouse:</strong> fast, columnar backend that stores everything cheaply and lets you run high-cardinality queries at speed. Your config.d/users.d overrides tune performance and access.</p><p><strong>SigNoz Query Service:</strong> API layer that turns UI/alert queries into ClickHouse SQL and returns results quickly; the UI and alerting engine talk to this.</p><p><strong>SigNoz UI:</strong> one console for traces, logs, metrics, dashboards, and alerts — jump from a spike to the exact trace/log in a few clicks.</p><p><strong>Alerting:</strong> rules run against data via the query service; when thresholds breach, notifications go to Slack/email/webhooks/etc.</p><p><strong>Whole flow (in one breath):</strong> apps → OTLP → <strong>Collector</strong> → <strong>ClickHouse</strong>; then <strong>Query Service</strong> + <strong>UI</strong> read from ClickHouse for charts/traces/logs, and <strong>Alerting</strong> evaluates rules and pings you. If you’re fronting with Nginx: / → UI, /otlpgrpc → gRPC 4317, /v1/* → HTTP 4318.</p><h3>What the key files do (and why)</h3><p>I am not gonna share each file as it will depend on your config, goal is to show the main entry point and how this setup is working.</p><h3>1) scripts/bootstrap_signoz.sh</h3><p><strong>Purpose:</strong> One-command bootstrap for a fresh EC2 (or any Linux box).<br> <strong>What it handles:</strong></p><ul><li>Installs Docker &amp; Docker Compose</li><li>Pulls SigNoz images</li><li>Creates volumes and copies your overrides (Nginx, ClickHouse, etc.)</li><li>Brings everything up in the right order</li><li>(Optional) Opens firewall ports or sets up UFW</li><li>Health checks &amp; first-run sanity checks</li></ul><pre>set -euo pipefail<br><br>: &quot;${SIGNOZ_REF:=v0.94.1}&quot;          <br>: &quot;${ROOT_DIR:=$PWD}&quot;            <br>: &quot;${TARGET_DIR:=$ROOT_DIR/.vendor/signoz}&quot;  <br>: &quot;${JWT_SECRET:=change-this-now}&quot;   <br>: &quot;${CLICKHOUSE_VERSION:=25.5.6}&quot;<br>: &quot;${OTELCOL_TAG:=v0.129.4}&quot;<br><br>echo &quot;==&gt; Using SigNoz ref: ${SIGNOZ_REF}&quot;<br>echo &quot;==&gt; Cloning into:     ${TARGET_DIR}&quot;<br><br>mkdir -p &quot;$(dirname &quot;$TARGET_DIR&quot;)&quot;<br><br>if [ -d &quot;$TARGET_DIR/.git&quot; ]; then<br>  echo &quot;==&gt; Repo exists, fetching updates...&quot;<br>  git -C &quot;$TARGET_DIR&quot; fetch --tags --all<br>  git -C &quot;$TARGET_DIR&quot; checkout --force &quot;$SIGNOZ_REF&quot;<br>  if git -C &quot;$TARGET_DIR&quot; show-ref --verify --quiet &quot;refs/remotes/origin/${SIGNOZ_REF}&quot;; then<br>    git -C &quot;$TARGET_DIR&quot; reset --hard &quot;origin/${SIGNOZ_REF}&quot;<br>  fi<br>else<br>  git clone -b &quot;$SIGNOZ_REF&quot; https://github.com/SigNoz/signoz.git &quot;$TARGET_DIR&quot;<br>fi<br><br>cd &quot;$TARGET_DIR/deploy/docker&quot;<br><br>cat &gt; .env.override &lt;&lt;EOF<br>CLICKHOUSE_IMAGE=clickhouse/clickhouse-server:${CLICKHOUSE_VERSION}<br>SIGNOZ_IMAGE=signoz/signoz:${SIGNOZ_REF}<br>OTEL_COLLECTOR_IMAGE=signoz/signoz-otel-collector:${OTELCOL_TAG}<br>JWT_SECRET=${JWT_SECRET}<br>EOF<br><br><br>if ! docker network ls | grep -q signoz-network; then<br>  echo &quot;==&gt; Creating Docker network: signoz-network&quot;<br>  docker network create signoz-network<br>else<br>  echo &quot;==&gt; Docker network already exists: signoz-network&quot;<br>fi<br><br>if [ ! -f &quot;$ROOT_DIR/signoz-override/docker-compose.override.yml&quot; ]; then<br>  echo &quot;ERROR: Missing override file at $ROOT_DIR/signoz_override/docker-compose.override.yml&quot;<br>  exit 1<br>fi<br><br>echo &quot;==&gt; Starting SigNoz stack…&quot;<br>docker compose \<br>  --env-file .env.override \<br>  -f docker-compose.yaml \<br>  -f $ROOT_DIR/signoz-override/docker-compose.override.yml \<br>  up -d --remove-orphans<br><br><br>echo &quot;==&gt; SigNoz Containers:&quot;<br>docker compose ps<br><br>echo &quot;==&gt; UI should be on: http://&lt;your-ec2-ip&gt;:8080 or Direct (no Nginx): http://&lt;ec2-ip&gt;:8080, Via Nginx: http://&lt;domain&gt;&quot;<br>echo &quot;==&gt; OTLP gRPC: :4317, OTLP HTTP: :4318&quot;<br><br># --- Now bring up Nginx reverse proxy ---<br>echo &quot;==&gt; Starting Nginx proxy stack...&quot;<br>cd ~/signoz/nginx<br>docker compose up -d<br><br>echo &quot;==&gt; Deployment complete!&quot;</pre><h3>2) signoz-override/docker-compose.override.yml</h3><p><strong>Purpose:</strong> Customize the official SigNoz docker stack without touching upstream files.<br> <strong>What it handles:</strong></p><ul><li>Mounts your ClickHouse config overrides</li><li>Adds/changes environment variables</li><li>Adds Nginx reverse proxy service</li><li>Custom networks/labels/volumes</li></ul><pre>version: &quot;3.8&quot;<br><br>services:<br>  clickhouse:<br>    image: ${CLICKHOUSE_IMAGE}<br>    networks: [signoz-network]<br>    volumes:<br>      - clickhouse-data:/var/lib/clickhouse<br>      - ./clickhouse/config.d:/etc/clickhouse-server/config.d:ro<br>      - ./clickhouse/users.d:/etc/clickhouse-server/users.d:ro<br><br>  signoz:<br>    image: ${SIGNOZ_IMAGE}<br>    networks: [signoz-network]<br>    environment:<br>      - SIGNOZ_JWT_SECRET=${JWT_SECRET}<br>    # No public ports; UI goes via nginx<br><br>  otel-collector:<br>    image: ${OTEL_COLLECTOR_IMAGE}<br>    networks: [signoz-network]<br>    ports:<br>      - &quot;4317:4317&quot;   # OTLP gRPC<br>      - &quot;4318:4318&quot;   # OTLP HTTP<br>    # Optional: mount custom collector config if you add one later<br>    # volumes:<br>    #   - ./otel-collector/config.yaml:/etc/otelcol/config.yaml:ro<br><br>volumes:<br>  clickhouse-data:<br><br>networks:<br>  signoz-network:<br>    external: true</pre><p><strong>Why Nginx at all?</strong></p><ul><li>Single, friendly entrypoint (:80 / :443)</li><li>TLS termination and HSTS</li><li>Optional Basic Auth or IP allowlists</li><li>Small layer for rate limiting &amp; headers</li><li>Clean separation so SigNoz containers stay on an internal network</li></ul><p><strong>Example </strong><strong>default.conf and docker-compose.yml:</strong></p><pre>upstream signoz_ui { server signoz:8080; }<br>upstream otel_grpc { server signoz-otel-collector:4317; }<br>upstream otel_http { server signoz-otel-collector:4318; }<br><br>server {<br>    listen 80;<br>    server_name your.domain.com;<br><br>    client_max_body_size 25m;<br>    proxy_read_timeout   3600s;<br>    proxy_send_timeout   3600s;<br><br>    location / {<br>        proxy_set_header Host $host;<br>        proxy_set_header X-Real-IP $remote_addr;<br>        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>        proxy_set_header X-Forwarded-Proto $scheme;<br>        proxy_pass http://signoz_ui;<br>    }<br><br>    location = /otlpgrpc {<br>        grpc_read_timeout  3600s;<br>        grpc_send_timeout  3600s;<br>        grpc_set_header    TE trailers;<br>        grpc_pass          grpc://otel_grpc;<br>    }<br><br>    location /v1/ {<br>        proxy_http_version 1.1;<br>        proxy_set_header   Host $host;<br>        proxy_set_header   X-Real-IP $remote_addr;<br>        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;<br>        proxy_set_header   X-Forwarded-Proto $scheme;<br>        proxy_pass         http://otel_http;<br>    }<br>}</pre><pre>version: &quot;3.8&quot;<br><br>services:<br>  nginx-proxy:<br>    image: nginx:latest<br>    container_name: nginx-proxy<br>    restart: unless-stopped<br>    ports:<br>      - &quot;80:80&quot;<br>      - &quot;443:443&quot;<br>    volumes:<br>      - ./conf.d:/etc/nginx/conf.d<br>      - ./certs:/etc/letsencrypt<br>      - ./html:/usr/share/nginx/html<br>    networks:<br>      - signoz-network<br><br>  certbot:<br>    image: certbot/certbot:latest<br>    container_name: certbot<br>    volumes:<br>      - ./certs:/etc/letsencrypt<br>      - ./html:/usr/share/nginx/html<br>    entrypoint: /bin/sh<br>    networks:<br>      - signoz-network<br><br>networks:<br>  signoz-network:<br>    external: true</pre><h3>5) Clickhouse (storage ): clickhouse/config.d/&lt;custom-config.xml&gt;</h3><p>in most of the cases the default config works fine, but in case you wanna fine tune the clickhouse config according to machine or anyhthing else, you can do that too by writing custom configs in config.d and users.d folders</p><p>for example : I modifed the ttl of system logs from 30 days to 7 days. to save some storage and configured system resources given to clickhouse.</p><p>this is a very simple setup which i created for deploying signoz within few hours, now you just need to configure your loggers in your microservices to export logs to otel collector. <br>there are several approaches of that too. <br>most simple one is to directly send logs to signoz-otel-collector endpoint via grpc or http.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4MViZcBdTyaoNRHiLnKiuw.png" /><figcaption>source : signoz official blog</figcaption></figure><h3><strong>Conclusion :</strong></h3><p>In our case, this simple setup has already saved us hours of blind debugging and given us confidence that issues won’t slip by unnoticed.</p><p>The best part is that this stack grows with you:</p><ul><li>Start with logs and dashboards, add metrics and traces when you’re ready.</li><li>Hook alerts to Slack or email so you know about problems in real time.</li></ul><p>If you’re running microservices on a budget, SigNoz is one of the most practical ways to get <strong>production-grade observability</strong> without burning through cash.</p><p>Now that your base stack is live, the next step is simple: configure your loggers to export directly to the OTEL collector, explore the built-in dashboards, and set up your first alert. From there, you’ll never want to go back to grepping Docker logs again or simple otel tools.</p><p><strong>Few articles which i referred:</strong></p><ul><li>Different setups to send logs to signoz :</li></ul><p><a href="https://signoz.io/docs/userguide/logs/">Get Started with Logs in SigNoz</a></p><ul><li>All logger libraries which can be used to export logs :</li></ul><p><a href="https://signoz.io/docs/logs-management/send-logs-to-signoz/">Send logs to SigNoz</a></p><ul><li>Alerts in signoz :</li></ul><p><a href="https://signoz.io/docs/userguide/alerts-management/">Alerts</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b16ce02f778" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[High level architecture of real-time voice agents]]></title>
            <link>https://medium.com/@tyagishashank118/high-level-architecture-of-real-time-voice-agents-ddcedb251fc4?source=rss-b35e56aa4b3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddcedb251fc4</guid>
            <category><![CDATA[text-to-speech]]></category>
            <category><![CDATA[ai-voice-agent]]></category>
            <category><![CDATA[conversational-ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Shashank Tyagi]]></dc:creator>
            <pubDate>Tue, 09 Sep 2025 05:16:13 GMT</pubDate>
            <atom:updated>2025-09-09T05:16:13.183Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6AHZzSMAEGj5EQtVQ_3kTg.png" /></figure><p>At a high level, a <strong>Voice Agent</strong> is a conversational AI system that can <em>listen, understand, and respond</em> to spoken queries in real time. To achieve this, the architecture combines <strong>speech processing</strong>, <strong>language reasoning</strong>, and <strong>network communication</strong> layers.</p><h3>1. Communication Foundations: HTTP vs WebRTC</h3><h3>HTTP-Based Voice AI (Tradition)</h3><p>The client (phone, Alexa, Siri, etc.) records your full speech.After you finish speaking, it <strong>uploads the audio file</strong> to the server over HTTP.The server processes it (STT → LLM → TTS) and returns the audio reply.</p><p>Drawback: <strong>High latency</strong> because the system waits until you finish speaking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qWme0bMtQlknY8COsDVCOA.png" /><figcaption>sourced from learn.deeplearning.ai</figcaption></figure><h3>Stateful / Persistent Connections</h3><p>Instead of waiting for the whole recording, the client <strong>streams speech continuously</strong> to the server. The server also streams back responses. This allows <strong>real-time conversations</strong> where the system can interrupt, backchannel (“uh-huh”), or overlap speech.</p><h3>Why WebRTC?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KHm3dXWOu86azUT0rahy_w.png" /></figure><p>WebRTC (Web Real-Time Communication) is the modern protocol used to enable <strong>real-time, low-latency, peer-to-peer communication</strong> in browsers and apps.</p><p><strong>Built on UDP:</strong> Unlike TCP, UDP doesn’t wait for lost packets to be retransmitted. This reduces lag — crucial for real-time speech.</p><p><strong>Full-duplex (both directions at once):</strong> Lets user and agent talk simultaneously.</p><p><strong>Optimized for media (voice/video):</strong></p><p>Congestion control (adjusts quality if network is slow).</p><p>Compression (reduces bandwidth).</p><p>Packet timestamps (keeps audio in sync).</p><p><strong>In short:</strong></p><p>HTTP = batch mode (slower).</p><p>WebRTC (UDP under the hood) = streaming mode (real-time).</p><h3>2. Core Components of a Voice Agent</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AChP0BrDlTEp-479XcVipA.png" /></figure><p>Here’s the <strong>Voice AI pipeline</strong>:</p><h3>1. Input Layer:</h3><p><strong>Voice Activity Detection (VAD):</strong> Detects if the user is speaking or silent.</p><p><strong>End-of-Utterance (EOU) Detection:</strong> Knows when the user has finished their turn (so the agent can reply).</p><h3>2. Speech-to-Text (STT / ASR):</h3><p>Converts raw audio into text.</p><p>Example: “Book me a table at 8 PM” → &quot;Book me a table at 8 PM&quot;</p><h3>3. Language Reasoning (LLM / Agent):</h3><p>Processes the text, understands intent, and generates a meaningful reply.</p><p>Can also use tools, APIs, or multimodal reasoning.</p><p>Example: LLM → &quot;Sure, booking a table at 8 PM at your usual restaurant.&quot;</p><h3>4. Text-to-Speech (TTS):</h3><p>Converts LLM’s text response back into human-like speech.</p><p>Example: &quot;Sure, booking a table at 8 PM&quot; → (audio waveform)</p><h3>5. Output Layer:</h3><p>May also include <strong>video/avatar output</strong> in advanced systems.</p><h3>3. Advanced Features in the Architecture</h3><h3>Turn Detection</h3><p>It Combines:</p><p><strong>VAD (audio-based):</strong> detects silence.</p><p><strong>Semantic Turn Detection (text-based):</strong> analyzes meaning of words (“is this sentence complete?”).</p><p><strong>Transformer models:</strong> predict end-of-utterance.</p><p>Result: The agent knows when to <strong>speak, pause, or wait</strong>.</p><h3>Interrupt Handling</h3><p>In real conversations, people interrupt each other. A Voice Agent must detect <strong>if the user interrupts</strong> while it’s speaking.</p><p>Flow: If interrupted → stop TTS → re-focus on new user input.</p><p>Prevents “robot talking over you” experience.</p><p>Final architecture comes out to be this :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JMjRoVN7Rd0UE6nAdXXU7A.png" /><figcaption>source : learn.deeplearning.ai</figcaption></figure><p><strong>WebRTC (UDP)</strong> enables real-time, human-like exchanges. <strong>VAD, EOU, Turn Detection, and Interruption Handling</strong> are what make interactions <em>feel natural</em>.</p><p>The biggest challenge is <strong>latency</strong>, but with streaming + smaller models, responses can approach human-level fluidity.</p><h3>Providers Across the Voice Agent Pipeline</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W4NkwLuZYxGkKPkXsJkpNA.png" /></figure><p>When building a Voice AI Agent, you don’t have to reinvent every component — there are specialized providers for each stage of the pipeline. Depending on your needs (latency, accuracy, cost, multilingual support, emotional tone), you can choose different vendors.</p><h3><strong>Conclusion</strong></h3><p>A modern Voice Agent is not a single monolithic system but a <strong>composition of best-in-class services</strong>.</p><p><strong>STT providers</strong> ensure speech is captured accurately in real time.</p><p><strong>LLM providers</strong> give reasoning and intelligence to interpret user intent.</p><p><strong>TTS providers</strong> bring the agent to life with natural, human-like voices.</p><p>Thanks to platforms like <strong>LiveKit</strong>, developers can stitch these pieces together without worrying about real-time transport and media pipelines. This modular ecosystem means you can <strong>mix-and-match providers</strong> depending on your application:</p><p>The end result is AI agents that can listen, think, and speak like humans in real time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddcedb251fc4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>