<?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 Afnan Shahid on Medium]]></title>
        <description><![CDATA[Stories by Afnan Shahid on Medium]]></description>
        <link>https://medium.com/@afnanshahid1992?source=rss-2fbfec4e6fe9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZTCKRvBNFvIHQ55_yQ2XPg.jpeg</url>
            <title>Stories by Afnan Shahid on Medium</title>
            <link>https://medium.com/@afnanshahid1992?source=rss-2fbfec4e6fe9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 17:09:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@afnanshahid1992/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[Ingesting Postgres Shards into a Redshift Data Warehouse with Kafka and Debezium]]></title>
            <link>https://engineering.touchbistro.com/ingesting-postgres-shards-into-a-redshift-data-warehouse-with-kafka-and-debezium-2c1d8d487761?source=rss-2fbfec4e6fe9------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c1d8d487761</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[debezium]]></category>
            <category><![CDATA[redshift]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[etl]]></category>
            <dc:creator><![CDATA[Afnan Shahid]]></dc:creator>
            <pubDate>Mon, 20 Jul 2026 17:28:00 GMT</pubDate>
            <atom:updated>2026-07-20T17:31:00.010Z</atom:updated>
            <content:encoded><![CDATA[<h3>Background</h3><p>At TouchBistro, our primary data source is the Point of Sale (POS) application, an edge application responsible for taking orders, managing tables, and handling other operations that happen in physical restaurants. A single location can run several POS clients at once, and data flows from the POS to our backend as JSON payloads over a REST API.</p><p>When a payload arrives, two things happen in parallel. The data is written to a sharded Postgres system that supports our operational use cases, exposing fine-grained entities like bills and shifts to both TouchBistro users and third parties. At the same time, to support <em>analytical</em> use cases, we ran that same payload through a separate pipeline: the raw JSON was written to an S3 bucket, an SQS job picked it up and hydrated it with additional context, turned it into CSV, and dropped it back in S3, where several AWS Lambda functions running every five minutes upserted the data into Redshift, our analytical store.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5F5zeUCPVd_RDF2unqWkkg.png" /><figcaption>Our legacy lambda-based ETL architecture</figcaption></figure><p>That second pipeline was brittle and hard to maintain. Something as routine as adding a new column meant touching application code at several stages of the pipeline, and a failure anywhere in the chain could silently leave analytics data stale without anyone noticing until a report looked wrong. It was a lot of moving parts and application code to solve what is, at heart, a simple problem: getting operational data into an analytical store.</p><p>The data was already sitting in Postgres. So we asked ourselves: What if we skipped all the hydration machinery and replicated the shards downstream to Redshift directly, using change data capture (CDC)?</p><h3>CDC Primer</h3><p>Change data capture is a technique for tracking row-level changes: every insert, update, and delete, as they happen in a database.The naive approach is to poll: query the tables on a schedule and diff the results. That’s slow, adds load to the database, and can miss changes that happen between polls. Log-based CDC avoids this. Every transactional database already keeps a write-ahead log (the WAL in Postgres) that records every change before it’s committed, primarily for crash recovery and replication. CDC reads from that log.</p><p>The tool we ended up reaching for is Debezium, an open-source, log-based CDC platform built on top of Kafka Connect. A Debezium source connector reads a database’s transaction log, turns each committed change into an event, and streams it to a Kafka topic. Because it’s a passive reader of a log the database already maintains, it captures every change in order with minimal overhead on the source, rather than hammering it with queries. From Kafka, those change events can fan out to whatever downstream systems need them. The piece that does that fanning-out is a sink connector: where a source connector reads changes into Kafka, a sink connector reads them back out and writes them to a target system, in our case, Redshift.</p><h3>The False Starts</h3><p>We didn’t want to build something ourselves if we didn’t have to, so we evaluated a few existing solutions first.</p><p><strong>Fivetran and ZeroETL: </strong>We first considered Fivetran, but the cost was prohibitive and given the data engineering expertise we’d already built in-house, it was hard to justify it.</p><p>Next, we explored ZeroETL, a brand-new AWS offering aimed squarely at this problem: it replicates data from an Aurora PostgreSQL setup into Redshift. Unfortunately, it didn’t work with our sharded architecture. ZeroETL would have replicated every table in each of our ten physical shards as its own table in Redshift, which would have left us needing yet another process to merge the shards back into single logical tables, which is exactly the kind of complex machinery we were trying to get rid of. On top of that, it didn’t integrate with our observability tooling (we rely on Datadog), and it became apparent to us that the product was still in its infancy and hadn’t been battle-tested at scale.</p><p><strong>Streaming: </strong>When exploring Debezium, the most direct implementation, a sink connector that writes straight into Redshift, with the<a href="https://debezium.io/documentation/reference/stable/connectors/jdbc.html"> JDBC Sink Connector</a>, was the first thing we tried, and the first thing we abandoned.</p><p>The biggest limitation surfaced quickly, the sink connector doesn’t natively support a Redshift dialect. We tried using the Postgres dialect first, since Redshift speaks the Postgres wire protocol and is forked from PostgreSQL 8.0.2. But the dialect broke down in the upsert mode. In upsert mode, the connector’s Postgres dialect generates INSERT ... ON CONFLICT (pk) DO UPDATE SET ... statements. That syntax fails on Redshift, ON CONFLICT was introduced in PostgreSQL 9.5, years after Redshift forked, so Redshift simply doesn&#39;t parse it.So we forked the JDBC sink connector and wrote our own Redshift dialect, which handled upserts in three steps:</p><ol><li>Batch-inserting the incoming Kafka records into a temporary staging table.</li><li>Deleting any matching records from the destination table</li><li>Inserting the staged records into the destination.</li></ol><p>In our tests, however, the batch inserts into the staging table proved to be the bottleneck. With our largest table, we could only achieve a throughput of 63 records per second, far short of what we needed. We also ran into Redshift’s<a href="https://docs.aws.amazon.com/redshift/latest/dg/r_INSERT_30.html"> 16 MB limit on the size of a single SQL statement</a>, which capped how many rows we could pack into each batch insert.The root cause is architectural. Redshift is a columnar, OLAP database built for analytical queries over large volumes of data, not for transactional write patterns. It stores each column separately and distributes data across many nodes and slices, so a single small INSERT still forces work across the cluster, and committing each batch carries fixed overhead regardless of how few rows it touches. The way Redshift actually wants data is the COPY command, which loads large files from S3 in parallel across all slices at once, with orders of magnitude more throughput than streaming rows in through the JDBC sink.</p><h3>Enter Debezium</h3><p>Before walking through the pieces, here’s the shape of the final pipeline end to end: Postgres → Debezium → Kafka → an S3 data lake (as Parquet) → Airflow → Redshift. Each Postgres shard’s changes are captured by Debezium, streamed through Kafka, landed in S3 as Parquet files, and finally loaded into Redshift by a scheduled Airflow job. The sections below walk through each stop in that order.</p><p><strong>Debezium Source Connector: </strong>At the heart of our new data pipeline is Debezium, an open-source project built on top of Kafka that uses Kafka Connect to capture row-level changes by hooking into the database’s transaction log. Since we run on AWS, we opted for the managed versions of Kafka (MSK) and Kafka Connect (MSK Connect). Getting Debezium working required enabling logical replication on all of our Postgres instances by setting wal_level to logical. Out of the box, the events Debezium produces are verbose: each change arrives as an envelope containing the row&#39;s before state, its after state, and a block of metadata. Since we only cared about the new state of each row for INSERT and UPDATE events, we used the io.debezium.transforms.ExtractNewRecordState transform to flatten that envelope down to just the after payload.</p><p><strong>Kafka and the Schema Registry: </strong>At the center of our pipeline sits Kafka and the schema registry. A schema registry is a separate service that stores the schema for each topic centrally and hands out an ID for each version, so producers and consumers can agree on structure without shipping the full schema in every message. We kept things simple here, allowing Debezium to automatically create new Kafka topics whenever a new table is published to Postgres. During benchmarking, one thing stood out: our compute resources were severely under-utilized while cluster storage was almost always full. That painted a clear picture, we could afford to do more work at write and read time to save on storage.</p><p>We decided to serialize the JSON events produced by Debezium as Avro in our Kafka Connect worker config, and to compress the Avro data with the Snappy codec. The savings were substantial: cluster storage utilization dropped to just 30 percent at any given time. Using Avro with Debezium requires a schema registry, so we went with the Glue schema registry. With the default JSON format, Debezium encodes the full schema in every event payload; with Avro, each event carries only a reference to the schema in the registry, which dramatically reduces storage. The primary trade-off is that Avro isn’t human-readable, so you lose the ability to casually inspect data on the cluster.</p><p><strong>S3 Sink Connector: </strong>At the very end of our pipeline sits the S3 sink connector, which we configured to write Parquet files aggressively, flushing to the bucket every minute. The sink connector doesn’t write each record to S3 individually; it batches incoming records into a file held open in memory and periodically “rotates” that file by closing it and flushing it to the bucket. How and when it decides to rotate is controlled by a couple of settings, and getting them right turned out to matter more than we expected. We set rotate.interval.ms to -1 to disable it entirely. setting uses a record-based timestamp extractor and only rotates a file when a subsequent record&#39;s timestamp exceeds the interval, which means that if a topic partition stops receiving records, the open file just sits there indefinitely. Instead, we set rotate.schedule.interval.ms to 60000 ms, which guarantees records are actively flushed to S3 every minute regardless of whether new records arrive. The trade-off is that the sink connector now provides at-least-once delivery guarantees rather than exactly-once. In practice that means a record can occasionally be written to S3 more than once, so anything reading from the data lake downstream has to be able to tolerate duplicates, which, as we&#39;ll see later, shaped how we designed the Redshift load.</p><p>For the remaining configuration, we set timestamp.extractor to Wallclock and path.format to year&#39;=YYYY/&#39;month&#39;=MM/&#39;day&#39;=dd/&#39;hour&#39;=HH/&#39;minute&#39;=mm. We also used topics.regex instead of topics so that new tables added to Postgres automatically stream to the S3 bucket without any config changes.</p><p><strong>Airflow: </strong>The final step of the pipeline was getting the raw Parquet files into Redshift, and we knew the process had to be idempotent. We leaned heavily on Airflow’s temporal processing semantics to make that happen.</p><p>The core challenge was that our data lake had a separate prefix path per shard for each table, but in Redshift each table existed as a single logical table. Redshift’s manifest file feature solved this neatly, a manifest lets you enumerate an explicit list of files for a single COPY statement. We couldn&#39;t simply point a single COPY at one S3 prefix, because the files for one logical table were scattered across ten shard-specific prefixes, and COPY loads from one location at a time. At a high level, our process(which we wrote as batch Python script) collects the prefix paths of the Parquet files across all ten shards, writes them into a manifest file, COPYs the files into a staging table, and then performs an upsert into the final destination table. We initially used Redshift&#39;s native MERGE statement to move data from staging into the destination, but in our tests it proved slower than a manual delete-and-insert: joining on the staging table to first delete matching records from the destination, then inserting the full contents of the staging table.We used Airflow&#39;s data_interval_start and data_interval_end macros to scope each run to a precise time window, which makes replaying any pipeline run safe, no duplicates ever land in the destination tables. We also added a two-minute look-back to every batch ingestion run, for reasons we&#39;ll explain in the next section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FPeGNMz8omQsl0eTXcehcg.png" /><figcaption>Our new debezium-based architecture</figcaption></figure><h3>Challenges</h3><p>While productionizing this setup, we ran into a few challenges worth sharing.</p><p><strong>Initial Snapshot: </strong>When Debezium first starts replicating, it begins by capturing a consistent snapshot of all tables, holding onto a replication slot until every record from the initial snapshot has been streamed to Kafka. For us, this made the initial snapshot extremely slow ,and because WAL segments accumulate while the slot is pinned, it puts serious pressure on our infrastructure from a storage perspective. This is a well-documented pain point: plenty of companies have written about it, and the Debezium team has been steadily improving the snapshotting process. Their main answer is the incremental snapshot rather than holding onto the replication slot for the entire snapshot phase, Debezium interleaves two streams, reading the initial state of the tables in chunks while simultaneously streaming the changes that arrive after the slot was created. The Debezium team has written about the approach in detail<a href="https://debezium.io/blog/2021/10/07/incremental-snapshots/"> here</a>.</p><p>We knew we had to solve this problem, and our solution came from reverse engineering Debezium’s initial snapshotting process. We studied the Debezium source code along with Gunnar Morling’s excellent talk on the subject, which you can find<a href="https://www.youtube.com/watch?v=Lp0Rg8_nxUs&amp;t=666s"> here</a>.</p><p>We then built a Python utility script that does the following:</p><ol><li>Creates a replication slot and a publication, capturing the current position in the transaction log (LSN).</li><li>Opens a transaction pinned to that consistent snapshot and exports the state of the database to an S3 bucket as CSV, using the Aurora extension aws_s3.query_export_to_s3.</li><li>Loads the exported data from S3 into Redshift using the COPY command.</li></ol><p>The handoff to the source connector is then just configuration. We point the Debezium Postgres connector at the pre-created slot (slot.name) and publication (publication.name), and set snapshot.mode to no_data, telling it to skip its own initial snapshot. On startup, the connector attaches to the existing slot and begins streaming from the slot&#39;s stored position, the same LSN the snapshot was cut at.</p><p><strong>Look-back window: </strong>During our testing, we noticed that some records weren’t being ingested from the data lake into our Redshift destination tables. The culprit turned out to be the rotate.schedule.interval.ms setting. To explain this more concretely, let’s walk through an example.</p><ul><li>At <strong>11:10:59</strong> — A record arrives on a topic partition. The connector opens a new file for it. Because the Wallclock extractor stamps records with the current system time, this record is destined for the minute=10 folder in S3.</li><li>Between <strong>11:10:59 → 11:11:58</strong> — The file stays open, waiting for more records. The scheduled rotation clock started when the <em>first</em> record was written, not at the top of the minute.</li><li>At <strong>~11:11:59</strong> — The 60-second rotation interval elapses. The file is flushed, uploaded to S3 into …/hour=11/minute=10/, and the offsets are committed.</li></ul><p>Notice what happened: the minute=10 folder didn’t receive its final file until nearly the end of minute 11. The downstream Airflow job that ran at 11:11:00 and read the minute=10 folder would have silently missed that record.</p><p>The fix was simple, our downstream Airflow job always looks back two minutes. When the job runs for minute 11, it processes minute=10, minute=09 and minute=08 folders by which point every file destined for that folder is guaranteed to have been committed, since the maximum delay is one rotation interval (plus a few seconds of upload time). In exchange for two minutes of added latency, we get folders we can treat as immutable and complete.</p><p>One more operational problem we had to account for was Redshift’s weekly maintenance window, during which the cluster can be unavailable for up to 30 minutes. Our EL pipeline checks whether a maintenance window has just ended, and if so, reprocesses the previous 30 minutes of data to pick up anything that failed to load while the cluster was down.</p><p><strong>Controlling column names:</strong> We chose Parquet as the file format for our data lake, and the choice came after careful consideration. One of the primary reasons was how the S3 sink connector handles dates and timestamps: with Parquet they come through naturally, whereas with Avro they’re written as epoch values. Choosing Avro would have meant adding transformations downstream or alternatively, setting Debezium’s time.precision.mode config to isostring.</p><p>Parquet did come with implications for the Redshift side of the pipeline, however. Redshift’s COPY command doesn&#39;t let you specify a column list when loading Parquet files, which meant column ordering became something we had to control explicitly in the Debezium config. It also imposed a strict sequence on schema changes: whenever we add a new column, it has to land in Redshift first, and only then in the Debezium config.</p><p><strong>Observability: </strong>We care deeply about observability at TouchBistro. Debezium provides detailed metrics out of the box, but unfortunately MSK Connect doesn’t expose the JMX endpoint they’re published to, since AWS doesn’t grant direct access to the underlying hosts. Because we already had robust CI/CD infrastructure in place (we use<a href="https://github.com/Shopify/shipit-engine"> shipit</a>) which made it easy to build and deploy a custom version of the connector, we decided to override the start method of Debezium’s PostgresSourceConnector class and publish the metrics directly to Datadog.</p><h3>The Final Result</h3><p>After several months of trying different solutions and methods, we finally landed on one that we were happy with. The new pipeline now replicates 5 million records per day from Postgres to Redshift, powering the 60+ reports our customers rely on to run their restaurants. Collectively, our users view over 100,000 years’ worth of reporting data every month. Since launch, we’ve had zero downtime, and schema changes that used to require manual intervention are now seamless: adding a new column in Postgres and replicating its records to Redshift just works. The pipeline primarily serves as the EL of our data stack, the tables it populates are transformed into dimensions and facts using dbt.</p><p>This project was a great learning experience for our small team of engineers. We wanted to give back to the open source community, because without the wonderful work that went into the Debezium project, we couldn’t have delivered insightful analytics to our customers.</p><p>&gt; Does TouchBistro sound like somewhere you might like to work? We are always looking for talented new team members. Check out<a href="https://www.touchbistro.com/careers/#open-positions"> </a><a href="https://www.touchbistro.com/careers/#open-positions">TouchBistro Careers &amp; Job Opportunities</a> to find the role that is right for you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c1d8d487761" width="1" height="1" alt=""><hr><p><a href="https://engineering.touchbistro.com/ingesting-postgres-shards-into-a-redshift-data-warehouse-with-kafka-and-debezium-2c1d8d487761">Ingesting Postgres Shards into a Redshift Data Warehouse with Kafka and Debezium</a> was originally published in <a href="https://engineering.touchbistro.com/">TouchBistro Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>