<?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 Devesh K Sharma on Medium]]></title>
        <description><![CDATA[Stories by Devesh K Sharma on Medium]]></description>
        <link>https://medium.com/@deveshsharmaanalytics?source=rss-68daf19e5af2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*osXK2dO81l5gr7BHkuOZqQ@2x.jpeg</url>
            <title>Stories by Devesh K Sharma on Medium</title>
            <link>https://medium.com/@deveshsharmaanalytics?source=rss-68daf19e5af2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 20:33:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@deveshsharmaanalytics/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[Kafka and Microservices: A Practitioner’s Deep Dive into Implementation, Patterns, and Hard-Won…]]></title>
            <link>https://medium.com/@deveshsharmaanalytics/kafka-and-microservices-a-practitioners-deep-dive-into-implementation-patterns-and-hard-won-5199ca3b14f3?source=rss-68daf19e5af2------2</link>
            <guid isPermaLink="false">https://medium.com/p/5199ca3b14f3</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <dc:creator><![CDATA[Devesh K Sharma]]></dc:creator>
            <pubDate>Sun, 10 May 2026 15:09:20 GMT</pubDate>
            <atom:updated>2026-05-10T15:20:01.235Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kafka and Microservices: A Practitioner’s Deep Dive into Implementation, Patterns, and Hard-Won Tradeoffs</h3><p><em>Event sourcing, CQRS, the Saga pattern, schema governance, and the failure modes nobody puts in the pitch deck — with real code throughout</em></p><p>There’s a version of this article that starts with “Kafka is amazing and you should use it everywhere.” This isn’t that article.</p><p>I’ve built event-driven microservices architectures that worked beautifully and ones that became operational nightmares — sometimes on the same project, six months apart. The difference was almost never the technology. It was the depth of understanding the team brought to the design decisions before the first kafka-topics --create command ran.</p><p>This is a long article. It covers implementation, real-world patterns, and the tradeoffs that tend to be buried under the excitement. If you’re looking for a five-minute overview, this isn’t it. If you’re about to commit a production system to an event-driven architecture, read all of it.</p><h3>Part 1 — Why Microservices Needed a Different Communication Model</h3><p>When teams decompose monoliths into microservices, the instinct is to wire them together the way the monolith was wired internally — function calls, but over HTTP. Service A calls Service B, waits, then continues.</p><p>This works. Until it doesn’t.</p><h3>The problems with synchronous HTTP at scale</h3><p><strong>Tight temporal coupling.</strong> If Service B is slow, Service A waits. If Service B is down, Service A fails. You have split the deployment but preserved every failure dependency of the monolith.</p><p><strong>Cascading failures and retry storms.</strong> A spike in load on one service backs up the call chain. Every service upstream adds its own timeouts and retries. What started as latency in one service becomes a retry storm that looks like a DDoS to everything downstream.</p><p><strong>Schema coupling at runtime.</strong> Service A calls Service B’s /providers endpoint. Service B changes the response shape. Service A breaks — not at compile time, not at deploy time, but in production under load when someone is watching.</p><p><strong>Distributed transaction hell.</strong> A patient enrollment workflow touches five services: eligibility check, provider assignment, benefits activation, notification, billing. Orchestrating this over synchronous HTTP requires one service to hold all the state, handle all the failures, and manage all the retries. That coordinator becomes your most critical and most fragile service. And you haven’t actually solved distributed consistency — you’ve just moved the problem somewhere it’s harder to see.</p><p>Kafka changes the communication model fundamentally. Instead of Service A calling Service B, Service A publishes an event and is done. Service B — and Service C, and Service D — subscribe and react in their own time. The dependency direction inverts. Producers are ignorant of consumers.</p><h3>Part 2 — Kafka Architecture: What You Actually Need to Know</h3><p>Before writing a line of code, you need to understand the components precisely, because the design decisions you make at this layer determine the operational characteristics of your entire system.</p><h3>The Log, Partitions, and Offsets</h3><p>Kafka is a <strong>distributed, durable, ordered log</strong>. It is not a message queue. The distinction is architectural, not semantic.</p><p>A traditional queue delivers a message to a consumer and deletes it. Kafka writes messages to a <strong>topic</strong>, which is partitioned and replicated across a broker cluster, and retains them for a configurable retention period — 7 days by default, but configurable to indefinite. Consumers maintain their own <strong>offset</strong> (their position in the log) and read at their own pace.</p><pre>Topic: provider-events (6 partitions, replication factor 3)</pre><pre>Partition 0: [offset 0] [offset 1] [offset 2] ... [offset 8,421]<br>Partition 1: [offset 0] [offset 1] [offset 2] ... [offset 7,903]<br>Partition 2: [offset 0] [offset 1] [offset 2] ... [offset 9,102]<br>...</pre><pre>Consumer Group A (MDM Service):     reading partition 0 at offset 8,419<br>Consumer Group B (Analytics):       reading partition 0 at offset 8,200  ← 221 behind<br>Consumer Group C (Audit Service):   reading partition 0 at offset 8,421  ← caught up</pre><p>Three consumer groups reading the same partition independently. Each at its own pace. Producer wrote once; three consumers consumed. This is the fundamental Kafka advantage over a queue.</p><h3>Partition Keys and Ordering Guarantees</h3><p>Kafka guarantees ordering <strong>within a partition</strong>, not across partitions. Messages with the same partition key always land in the same partition, giving you per-key ordering.</p><p>python</p><pre># provider_id as partition key → all events for provider X land in the same partition<br># guarantees: ProviderCreated always before ProviderUpdated for the same provider</pre><pre>producer.produce(<br>    topic = &#39;provider-events&#39;,<br>    key   = provider_id,   # ← partition key<br>    value = json.dumps(event).encode()<br>)</pre><p>This is why partition key selection is a critical design decision. Choose a key too coarse (e.g., source_system) and you create hot partitions. Choose a key too fine (e.g., a UUID per event) and you lose ordering guarantees. Choose based on the entity that needs ordered processing — usually the primary entity ID.</p><h3>Consumer Groups and Parallelism</h3><p>A consumer group is a set of consumers that collectively read a topic. Kafka assigns partitions to consumers within the group — each partition is owned by exactly one consumer in the group at any time.</p><pre>Topic: provider-events (6 partitions)</pre><pre>Consumer Group: mdm-service<br>  Instance 1 → Partition 0, 1<br>  Instance 2 → Partition 2, 3<br>  Instance 3 → Partition 4, 5</pre><pre>Scale to 6 instances → each owns 1 partition<br>Scale beyond 6 instances → idle instances (no partition to own)</pre><p>This gives you a natural ceiling: <strong>you cannot have more active consumers in a group than partitions</strong>. Over-partition at topic creation — it’s cheaper to have unused partitions than to add partitions later (which triggers a rebalance and breaks per-key ordering guarantees).</p><h3>Producers: Delivery Guarantees and Idempotence</h3><p>Kafka producers have three delivery semantics, and the choice has real consequences:</p><p>python</p><pre># At-most-once: fire and forget, data loss possible<br>Producer({&#39;acks&#39;: &#39;0&#39;})</pre><pre># At-least-once: wait for leader ack, retries on failure → possible duplicates<br>Producer({&#39;acks&#39;: &#39;1&#39;, &#39;retries&#39;: 5})</pre><pre># Exactly-once: idempotent producer + leader + all in-sync replica acks<br>Producer({<br>    &#39;acks&#39;:                       &#39;all&#39;,       # wait for all in-sync replicas<br>    &#39;enable.idempotence&#39;:         True,        # producer assigns sequence numbers<br>    &#39;max.in.flight.requests.per.connection&#39;: 1 # maintain ordering with retries<br>})</pre><p>In practice, most systems use <strong>at-least-once delivery</strong> on the producer side and make consumers idempotent. Exactly-once semantics are available via Kafka transactions but come with throughput tradeoffs (roughly 30–40% lower). The idempotent-consumer approach is usually more operationally straightforward.</p><h3>Part 3 — Implementation: The Producer</h3><p>Let’s build a production-realistic provider event producer. Not a hello-world — something you’d actually run.</p><p>python</p><pre># provider_event_producer.py<br>import json<br>import uuid<br>import logging<br>from datetime import datetime, timezone<br>from dataclasses import dataclass, asdict<br>from confluent_kafka import Producer<br>from confluent_kafka.schema_registry import SchemaRegistryClient<br>from confluent_kafka.schema_registry.avro import AvroSerializer<br>from confluent_kafka.serialization import SerializationContext, MessageField</pre><pre>logger = logging.getLogger(__name__)</pre><pre># ── Event schema (registered in Schema Registry) ──────────────────<br>PROVIDER_EVENT_SCHEMA = &quot;&quot;&quot;<br>{<br>  &quot;type&quot;: &quot;record&quot;,<br>  &quot;name&quot;: &quot;ProviderEvent&quot;,<br>  &quot;namespace&quot;: &quot;com.healthcare.events&quot;,<br>  &quot;fields&quot;: [<br>    {&quot;name&quot;: &quot;event_id&quot;,        &quot;type&quot;: &quot;string&quot;},<br>    {&quot;name&quot;: &quot;event_type&quot;,      &quot;type&quot;: &quot;string&quot;},<br>    {&quot;name&quot;: &quot;schema_version&quot;,  &quot;type&quot;: &quot;string&quot;, &quot;default&quot;: &quot;1.0&quot;},<br>    {&quot;name&quot;: &quot;entity_id&quot;,       &quot;type&quot;: &quot;string&quot;},<br>    {&quot;name&quot;: &quot;entity_type&quot;,     &quot;type&quot;: &quot;string&quot;},<br>    {&quot;name&quot;: &quot;occurred_at&quot;,     &quot;type&quot;: &quot;string&quot;},<br>    {&quot;name&quot;: &quot;correlation_id&quot;,  &quot;type&quot;: [&quot;null&quot;, &quot;string&quot;], &quot;default&quot;: null},<br>    {&quot;name&quot;: &quot;source_system&quot;,   &quot;type&quot;: &quot;string&quot;},<br>    {&quot;name&quot;: &quot;payload&quot;,         &quot;type&quot;: {&quot;type&quot;: &quot;map&quot;, &quot;values&quot;: &quot;string&quot;}}<br>  ]<br>}<br>&quot;&quot;&quot;</pre><pre>@dataclass<br>class ProviderEvent:<br>    event_type:     str<br>    entity_id:      str<br>    source_system:  str<br>    payload:        dict<br>    correlation_id: str  = None<br>    entity_type:    str  = &quot;Provider&quot;<br>    schema_version: str  = &quot;1.0&quot;</pre><pre>    def to_message(self) -&gt; dict:<br>        return {<br>            &quot;event_id&quot;:       str(uuid.uuid4()),<br>            &quot;event_type&quot;:     self.event_type,<br>            &quot;schema_version&quot;: self.schema_version,<br>            &quot;entity_id&quot;:      self.entity_id,<br>            &quot;entity_type&quot;:    self.entity_type,<br>            &quot;occurred_at&quot;:    datetime.now(timezone.utc).isoformat(),<br>            &quot;correlation_id&quot;: self.correlation_id,<br>            &quot;source_system&quot;:  self.source_system,<br>            &quot;payload&quot;:        {k: str(v) for k, v in self.payload.items()},<br>        }<br></pre><pre>class ProviderEventProducer:<br>    def __init__(self, bootstrap_servers: str, schema_registry_url: str):<br>        # Schema Registry enforces backward compatibility before publish<br>        sr_client = SchemaRegistryClient({&quot;url&quot;: schema_registry_url})<br>        self.serializer = AvroSerializer(sr_client, PROVIDER_EVENT_SCHEMA)</pre><pre>        self.producer = Producer({<br>            &quot;bootstrap.servers&quot;:                       bootstrap_servers,<br>            &quot;acks&quot;:                                    &quot;all&quot;,<br>            &quot;enable.idempotence&quot;:                      True,<br>            &quot;max.in.flight.requests.per.connection&quot;:   1,<br>            &quot;retries&quot;:                                 10,<br>            &quot;retry.backoff.ms&quot;:                        200,<br>            &quot;compression.type&quot;:                        &quot;snappy&quot;,  # ~4x compression<br>            &quot;linger.ms&quot;:                               5,         # batch for 5ms<br>            &quot;batch.size&quot;:                              65536,     # 64KB batch<br>        })</pre><pre>    def publish(self, event: ProviderEvent, topic: str = &quot;provider-events&quot;) -&gt; None:<br>        message = event.to_message()<br>        try:<br>            self.producer.produce(<br>                topic    = topic,<br>                key      = event.entity_id,   # partition key = provider ID<br>                value    = self.serializer(<br>                               message,<br>                               SerializationContext(topic, MessageField.VALUE)<br>                           ),<br>                headers  = {<br>                    &quot;correlation_id&quot;: event.correlation_id or &quot;&quot;,<br>                    &quot;source_system&quot;:  event.source_system,<br>                    &quot;event_type&quot;:     event.event_type,<br>                },<br>                callback = self._delivery_callback,<br>            )<br>            self.producer.poll(0)  # trigger callbacks without blocking<br>        except Exception as e:<br>            logger.error(f&quot;Failed to publish event: {e}&quot;, extra={&quot;event&quot;: message})<br>            raise</pre><pre>    @staticmethod<br>    def _delivery_callback(err, msg):<br>        if err:<br>            logger.error(f&quot;Delivery failed: {err}&quot;)<br>        else:<br>            logger.info(<br>                f&quot;Delivered {msg.topic()}[{msg.partition()}] offset={msg.offset()}&quot;<br>            )</pre><pre>    def flush(self, timeout: float = 10.0):<br>        remaining = self.producer.flush(timeout)<br>        if remaining &gt; 0:<br>            raise RuntimeError(f&quot;{remaining} messages not delivered within {timeout}s&quot;)<br></pre><pre># ── Usage ──────────────────────────────────────────────────────────<br>producer = ProviderEventProducer(<br>    bootstrap_servers    = &quot;kafka-1:9092,kafka-2:9092,kafka-3:9092&quot;,<br>    schema_registry_url  = &quot;http://schema-registry:8081&quot;<br>)</pre><pre>producer.publish(ProviderEvent(<br>    event_type    = &quot;ProviderSpecialtyChanged&quot;,<br>    entity_id     = &quot;prov-98765&quot;,<br>    source_system = &quot;credentialing-service&quot;,<br>    correlation_id= &quot;enroll-txn-abc123&quot;,    # traces saga across services<br>    payload       = {<br>        &quot;npi&quot;:           &quot;1234567890&quot;,<br>        &quot;old_specialty&quot;: &quot;207Q00000X&quot;,<br>        &quot;new_specialty&quot;: &quot;207R00000X&quot;,<br>        &quot;changed_by&quot;:    &quot;admin@health.org&quot;,<br>    }<br>))<br>producer.flush()</pre><p>A few things worth noting in this implementation: compression (Snappy gives ~4x reduction on JSON payloads), batching (linger.ms trades a small amount of latency for significantly higher throughput), headers for propagating correlation IDs without touching the Avro payload, and the Schema Registry serializer that enforces compatibility before the message reaches the broker.</p><h3>Part 4 — Implementation: The Consumer</h3><p>The consumer is where most of the failure modes live. Offset management, idempotency, and error handling are the three decisions that determine whether your consumer is reliable or unreliable.</p><p>python</p><pre># provider_event_consumer.py<br>import json<br>import logging<br>from confluent_kafka import Consumer, KafkaError, KafkaException<br>from confluent_kafka.schema_registry import SchemaRegistryClient<br>from confluent_kafka.schema_registry.avro import AvroDeserializer</pre><pre>logger = logging.getLogger(__name__)</pre><pre>class ProviderEventConsumer:<br>    def __init__(<br>        self,<br>        bootstrap_servers:   str,<br>        group_id:            str,<br>        schema_registry_url: str,<br>        topics:              list[str],<br>        processed_events_db, # your idempotency store (Redis, Postgres, etc.)<br>    ):<br>        sr_client = SchemaRegistryClient({&quot;url&quot;: schema_registry_url})<br>        self.deserializer = AvroDeserializer(sr_client)<br>        self.processed_events_db = processed_events_db</pre><pre>        self.consumer = Consumer({<br>            &quot;bootstrap.servers&quot;:        bootstrap_servers,<br>            &quot;group.id&quot;:                 group_id,<br>            &quot;auto.offset.reset&quot;:        &quot;earliest&quot;,<br>            &quot;enable.auto.commit&quot;:       False,     # ← manual commit only<br>            &quot;max.poll.interval.ms&quot;:     300000,    # 5min processing budget<br>            &quot;session.timeout.ms&quot;:       30000,<br>            &quot;heartbeat.interval.ms&quot;:    10000,<br>        })<br>        self.consumer.subscribe(topics)</pre><pre>    def consume(self, handler_fn, batch_size: int = 100):<br>        &quot;&quot;&quot;<br>        Poll → deserialise → idempotency check → process → commit.<br>        Only commits after successful processing — at-least-once delivery.<br>        &quot;&quot;&quot;<br>        try:<br>            while True:<br>                messages = self.consumer.consume(<br>                    num_messages = batch_size,<br>                    timeout      = 1.0<br>                )<br>                if not messages:<br>                    continue</pre><pre>                for msg in messages:<br>                    if msg.error():<br>                        if msg.error().code() == KafkaError.PARTITION_EOF:<br>                            continue<br>                        raise KafkaException(msg.error())</pre><pre>                    event = self.deserializer(<br>                        msg.value(), SerializationContext(msg.topic(), MessageField.VALUE)<br>                    )<br>                    event_id = event[&quot;event_id&quot;]</pre><pre>                    # ── Idempotency gate ──────────────────────────────<br>                    # At-least-once delivery means we may see the same<br>                    # event twice. Check before processing, record after.<br>                    if self.processed_events_db.exists(event_id):<br>                        logger.info(f&quot;Skipping duplicate event {event_id}&quot;)<br>                        continue</pre><pre>                    try:<br>                        handler_fn(event)<br>                        self.processed_events_db.record(event_id)<br>                    except RetryableError as e:<br>                        # transient failure: do NOT commit, let Kafka redeliver<br>                        logger.warning(f&quot;Retryable error on {event_id}: {e}&quot;)<br>                        continue<br>                    except PoisonPillError as e:<br>                        # unrecoverable: send to DLQ, commit, move on<br>                        logger.error(f&quot;Poison pill {event_id}: {e}&quot;)<br>                        self._send_to_dlq(msg, str(e))</pre><pre>                # Commit the entire batch after processing<br>                # If we crash here, the batch re-processes — idempotency handles it<br>                self.consumer.commit(asynchronous=False)</pre><pre>        except KeyboardInterrupt:<br>            pass<br>        finally:<br>            self.consumer.close()</pre><pre>    def _send_to_dlq(self, original_msg, error_reason: str):<br>        &quot;&quot;&quot;Route unprocessable messages to dead-letter topic for inspection.&quot;&quot;&quot;<br>        dlq_producer.produce(<br>            topic   = f&quot;{original_msg.topic()}.dlq&quot;,<br>            key     = original_msg.key(),<br>            value   = original_msg.value(),<br>            headers = {<br>                **dict(original_msg.headers()),<br>                &quot;dlq_error&quot;:       error_reason,<br>                &quot;dlq_original_ts&quot;: str(original_msg.timestamp()[1]),<br>            }<br>        )<br>        dlq_producer.flush()</pre><p>The key design decision here is enable.auto.commit: False. Auto-commit commits offsets on a timer regardless of whether your handler succeeded. That means a crash mid-processing results in silently lost events. Manual commit after confirmed processing gives you at-least-once delivery — you may process twice (idempotency handles it), but you never lose an event.</p><h3>Part 5 — Real-World Pattern: Event Sourcing</h3><p>Event sourcing replaces mutable state with an immutable sequence of events. Instead of a providers table with the current state of each provider, you have a provider_events table (or topic) containing every state change — ordered and permanent.</p><pre>provider_events topic:</pre><pre>offset 0: ProviderCreated        { npi: &quot;1234567890&quot;, name: &quot;Jane Doe&quot;, specialty: &quot;207Q00000X&quot; }<br>offset 1: AddressUpdated         { street: &quot;123 Main St&quot;, city: &quot;Chicago&quot; }<br>offset 2: SpecialtyChanged       { old: &quot;207Q00000X&quot;, new: &quot;207R00000X&quot; }<br>offset 3: CredentialExpired      { credential_type: &quot;DEA&quot;, expired_at: &quot;2025-01-15&quot; }<br>offset 4: ProviderDeactivated    { reason: &quot;license_lapsed&quot;, deactivated_by: &quot;compliance-service&quot; }</pre><p>Current state is derived by <strong>replaying</strong> the event stream:</p><p>python</p><pre>def rebuild_provider_state(events: list[dict]) -&gt; dict:<br>    &quot;&quot;&quot;<br>    Fold the event stream into current state.<br>    Called at startup or when a projection is stale.<br>    &quot;&quot;&quot;<br>    state = {}<br>    for event in events:<br>        event_type = event[&quot;event_type&quot;]<br>        payload    = event[&quot;payload&quot;]</pre><pre>        if event_type == &quot;ProviderCreated&quot;:<br>            state = {<br>                &quot;provider_id&quot;: event[&quot;entity_id&quot;],<br>                &quot;npi&quot;:         payload[&quot;npi&quot;],<br>                &quot;name&quot;:        payload[&quot;name&quot;],<br>                &quot;specialty&quot;:   payload[&quot;specialty&quot;],<br>                &quot;is_active&quot;:   True,<br>                &quot;version&quot;:     1,<br>            }<br>        elif event_type == &quot;SpecialtyChanged&quot;:<br>            state[&quot;specialty&quot;] = payload[&quot;new_specialty&quot;]<br>            state[&quot;version&quot;]  += 1</pre><pre>        elif event_type == &quot;ProviderDeactivated&quot;:<br>            state[&quot;is_active&quot;]         = False<br>            state[&quot;deactivation_reason&quot;] = payload[&quot;reason&quot;]<br>            state[&quot;version&quot;]           += 1</pre><pre>        # ... handle all event types</pre><pre>    return state</pre><h3>The Snapshot Pattern</h3><p>Replaying 50,000 events every time you need a provider’s current state is impractical. The <strong>snapshot pattern</strong> persists a point-in-time state capture alongside the event offset it was built from:</p><p>python</p><pre>@dataclass<br>class ProviderSnapshot:<br>    provider_id: str<br>    state:       dict<br>    at_offset:   int          # event log offset this snapshot was built from<br>    taken_at:    datetime</pre><pre>def get_provider_state(provider_id: str, event_store, snapshot_store) -&gt; dict:<br>    # Load latest snapshot (if any)<br>    snapshot = snapshot_store.get_latest(provider_id)</pre><pre>    if snapshot:<br>        # Only replay events since the snapshot<br>        events = event_store.get_events(<br>            entity_id    = provider_id,<br>            after_offset = snapshot.at_offset<br>        )<br>        state = rebuild_provider_state_from(snapshot.state, events)<br>    else:<br>        # No snapshot: replay everything<br>        events = event_store.get_all_events(provider_id)<br>        state  = rebuild_provider_state(events)</pre><pre>    # Take a new snapshot if we replayed more than N events<br>    if len(events) &gt; SNAPSHOT_THRESHOLD:<br>        snapshot_store.save(ProviderSnapshot(<br>            provider_id = provider_id,<br>            state       = state,<br>            at_offset   = events[-1][&quot;offset&quot;],<br>            taken_at    = datetime.now(timezone.utc)<br>        ))</pre><pre>    return state</pre><h3>The Real Advantage of Event Sourcing</h3><p>The replay capability is where event sourcing pays for itself in enterprise systems. A bug in your specialty normalisation logic produced six weeks of incorrect NUCC codes in the Gold layer. Without event sourcing, you’re reconstructing from backups or accepting the data loss.</p><p>With event sourcing: fix the logic, replay the event stream from six weeks ago, rebuild the projection. The original events are immutable — they are what happened. Your interpretation of them can be corrected.</p><h3>Part 6 — Real-World Pattern: CQRS</h3><p>CQRS — Command Query Responsibility Segregation — separates the write model from the read model. It pairs naturally with event sourcing and Kafka.</p><pre>┌─────────────────────────────────┐<br>                    │         WRITE SIDE               │<br>   Command          │                                  │<br>   (Update NPI) ──► │  ProviderCommandService          │<br>                    │  ↓ validate                      │<br>                    │  ↓ apply business rules          │<br>                    │  ↓ persist event to event store  │<br>                    │  ↓ publish to Kafka              │<br>                    └─────────────────────────────────┘<br>                                   │<br>                            Kafka topic:<br>                            provider-events<br>                                   │<br>              ┌────────────────────┼────────────────────┐<br>              ▼                    ▼                     ▼<br>    ┌──────────────────┐  ┌──────────────┐   ┌────────────────────┐<br>    │  Search Index    │  │  Dashboard   │   │  Analytics         │<br>    │  (Elasticsearch) │  │  (Redis)     │   │  (BigQuery)        │<br>    │                  │  │              │   │                    │<br>    │  Optimised for:  │  │ Optimised for│   │  Optimised for:    │<br>    │  full-text       │  │ low-latency  │   │  aggregations,     │<br>    │  provider search │  │ reads        │   │  HEDIS measures    │<br>    └──────────────────┘  └──────────────┘   └────────────────────┘<br>              ▲                    ▲                     ▲<br>         READ SIDE            READ SIDE             READ SIDE</pre><p>Each consumer maintains its own <strong>projection</strong> — a read-optimised view of the data built from the event stream. When a ProviderSpecialtyChanged event is published, three consumers independently update their projections:</p><p>python</p><pre># Elasticsearch projection updater<br>class SearchIndexProjection:<br>    def handle(self, event: dict):<br>        if event[&quot;event_type&quot;] == &quot;ProviderSpecialtyChanged&quot;:<br>            self.es_client.update(<br>                index  = &quot;providers&quot;,<br>                id     = event[&quot;entity_id&quot;],<br>                body   = {&quot;doc&quot;: {&quot;specialty&quot;: event[&quot;payload&quot;][&quot;new_specialty&quot;]}}<br>            )</pre><pre># Redis dashboard projection<br>class DashboardCacheProjection:<br>    def handle(self, event: dict):<br>        if event[&quot;event_type&quot;] in (&quot;ProviderSpecialtyChanged&quot;, &quot;ProviderDeactivated&quot;):<br>            # Invalidate cache; next read rebuilds from event store<br>            self.redis.delete(f&quot;provider:{event[&#39;entity_id&#39;]}:summary&quot;)</pre><pre># BigQuery analytics projection<br>class AnalyticsProjection:<br>    def handle(self, event: dict):<br>        # Append event to BQ streaming buffer<br>        self.bq_client.insert_rows_json(<br>            table  = &quot;analytics.provider_events&quot;,<br>            rows   = [self._to_bq_row(event)]<br>        )</pre><p>The write side doesn’t know these consumers exist. Add a new downstream system — a new analytics platform, a new regulatory report — without touching the write side or any existing consumer.</p><h3>The Consistency Gap</h3><p>CQRS introduces an eventual consistency window between write and read. A user updates a provider’s specialty. The command succeeds. They immediately navigate to the search results page, which reads from Elasticsearch. The specialty may still show the old value for some milliseconds.</p><p>Handle this with <strong>read-your-writes consistency</strong>: after a successful command, the client reads the write side’s response (which has the new state) directly, not the eventually-consistent read projection. Only subsequent reads from other sessions go to the projection.</p><h3>Part 7 — Real-World Pattern: The Saga</h3><p>A saga is a sequence of local transactions, each publishing an event that triggers the next step. If a step fails, compensating transactions undo the completed steps.</p><p>Consider a patient enrollment workflow spanning five services:</p><pre>EnrollmentService         EligibilityService       ProviderAssignmentService<br>       │                         │                          │<br>       │  EnrollmentInitiated    │                          │<br>       │────────────────────────►│                          │<br>       │                         │  EligibilityConfirmed    │<br>       │                         │─────────────────────────►│<br>       │                         │                          │  PCPAssigned<br>       │                         │                          │──────────────►<br>       │                         │                          │            ...<br>       │                         │                          │<br>       │     (if eligibility fails)                         │<br>       │                         │  EligibilityFailed       │<br>       │◄────────────────────────│                          │<br>  EnrollmentCancelled published  │                          │<br>  ← BenefitsService rolls back   │                          │<br>  ← NotificationService sends denial letter                 │</pre><p>python</p><pre># saga_step.py — the pattern every saga participant implements</pre><pre>class EligibilityService:<br>    def __init__(self, consumer: ProviderEventConsumer, producer: ProviderEventProducer):<br>        self.consumer = consumer<br>        self.producer = producer</pre><pre>    def handle_enrollment_initiated(self, event: dict):<br>        enrollment_id = event[&quot;payload&quot;][&quot;enrollment_id&quot;]<br>        member_id     = event[&quot;payload&quot;][&quot;member_id&quot;]<br>        correlation_id= event[&quot;correlation_id&quot;]</pre><pre>        try:<br>            # Local transaction — only touches eligibility service&#39;s own DB<br>            is_eligible = self.check_eligibility(member_id)</pre><pre>            if is_eligible:<br>                self.producer.publish(ProviderEvent(<br>                    event_type     = &quot;EligibilityConfirmed&quot;,<br>                    entity_id      = enrollment_id,<br>                    source_system  = &quot;eligibility-service&quot;,<br>                    correlation_id = correlation_id,   # ← MUST propagate<br>                    payload        = {<br>                        &quot;enrollment_id&quot;: enrollment_id,<br>                        &quot;member_id&quot;:     member_id,<br>                        &quot;plan_type&quot;:     &quot;HMO&quot;,<br>                        &quot;effective_date&quot;:&quot;2025-02-01&quot;,<br>                    }<br>                ))<br>            else:<br>                # Publish compensating event<br>                self.producer.publish(ProviderEvent(<br>                    event_type     = &quot;EligibilityFailed&quot;,<br>                    entity_id      = enrollment_id,<br>                    source_system  = &quot;eligibility-service&quot;,<br>                    correlation_id = correlation_id,<br>                    payload        = {<br>                        &quot;enrollment_id&quot;: enrollment_id,<br>                        &quot;reason&quot;:        &quot;member_not_found&quot;,<br>                    }<br>                ))</pre><pre>        except Exception as e:<br>            # System failure — publish failure event so saga can compensate<br>            self.producer.publish(ProviderEvent(<br>                event_type     = &quot;EligibilityCheckFailed&quot;,<br>                entity_id      = enrollment_id,<br>                source_system  = &quot;eligibility-service&quot;,<br>                correlation_id = correlation_id,<br>                payload        = {&quot;error&quot;: str(e), &quot;retryable&quot;: &quot;true&quot;}<br>            ))<br>            raise RetryableError(str(e))</pre><h3>The Idempotency Requirement</h3><p>Every saga step must be idempotent. Kafka delivers at-least-once — the same EnrollmentInitiated event may be delivered twice (rebalance, consumer restart, network blip). If EligibilityService processes it twice without idempotency, a member might be enrolled twice.</p><p>python</p><pre>def check_and_record_processed(event_id: str, db_conn) -&gt; bool:<br>    &quot;&quot;&quot;<br>    Insert event_id into processed_saga_events.<br>    Unique constraint prevents duplicate inserts.<br>    Returns False if already processed (duplicate delivery).<br>    &quot;&quot;&quot;<br>    try:<br>        db_conn.execute(<br>            &quot;INSERT INTO processed_saga_events (event_id, processed_at) VALUES (%s, NOW())&quot;,<br>            (event_id,)<br>        )<br>        db_conn.commit()<br>        return True   # first time we&#39;ve seen this event<br>    except UniqueViolation:<br>        db_conn.rollback()<br>        return False  # duplicate — skip processing</pre><h3>Saga vs Orchestration</h3><p>The pattern above is <strong>choreography</strong> — each service reacts to events and publishes its own. There is no central coordinator.</p><p>The alternative is <strong>orchestration</strong> — a central saga orchestrator explicitly tells each service what to do:</p><pre>EnrollmentOrchestrator<br>  → calls EligibilityService.check()<br>  → calls ProviderAssignmentService.assign()<br>  → calls BenefitsService.activate()<br>  → calls NotificationService.notify()</pre><p>Choreography scales better and removes the single-point-of-failure orchestrator. But it’s harder to reason about the overall flow — the business process is implicit in the event chain, not explicit in code. For long-running, complex sagas (more than 4–5 steps), an orchestrator with a state machine (AWS Step Functions, Temporal, or a custom saga state table) is often more maintainable.</p><h3>Part 8 — Schema Evolution: The Problem Nobody Talks About Until It’s Too Late</h3><p>This is the section that separates teams that run Kafka reliably from those that don’t.</p><h3>The Schema Registry Workflow</h3><p>Every event schema is registered in the Schema Registry before it can be published. The registry enforces a compatibility mode — backward, forward, or full — before accepting a new schema version.</p><pre>Producer wants to publish ProviderEvent v2<br>          │<br>          ▼<br>Schema Registry: &quot;Is v2 backward compatible with v1?&quot;<br>          │<br>    YES ──┤──► Assign schema ID 42; producer proceeds<br>          │<br>    NO ───┤──► Reject; producer fails with SchemaCompatibilityException</pre><p><strong>Backward compatible</strong> means new schema can read old messages. Adding optional fields with defaults is backward compatible. Removing fields is not.</p><p><strong>Forward compatible</strong> means old schema can read new messages. Removing optional fields is forward compatible. Adding required fields is not.</p><p><strong>Full compatible</strong> means both. This is the safest mode for production systems where you cannot guarantee all consumers upgrade simultaneously.</p><p>python</p><pre># Schema evolution — what&#39;s allowed with FULL compatibility</pre><pre># v1 ── SAFE: add optional field with default<br>{<br>  &quot;name&quot;: &quot;ProviderEvent&quot;,<br>  &quot;fields&quot;: [<br>    {&quot;name&quot;: &quot;event_id&quot;,       &quot;type&quot;: &quot;string&quot;},<br>    {&quot;name&quot;: &quot;event_type&quot;,     &quot;type&quot;: &quot;string&quot;},<br>    {&quot;name&quot;: &quot;entity_id&quot;,      &quot;type&quot;: &quot;string&quot;},<br>    {&quot;name&quot;: &quot;occurred_at&quot;,    &quot;type&quot;: &quot;string&quot;},<br>    # New in v2 — safe because it has a default:<br>    {&quot;name&quot;: &quot;schema_version&quot;, &quot;type&quot;: &quot;string&quot;, &quot;default&quot;: &quot;1.0&quot;},<br>    {&quot;name&quot;: &quot;correlation_id&quot;, &quot;type&quot;: [&quot;null&quot;, &quot;string&quot;], &quot;default&quot;: null}<br>  ]<br>}</pre><pre># NOT SAFE — renaming a field (old consumers break)<br>{&quot;name&quot;: &quot;provider_id&quot;}   # was &quot;entity_id&quot; — breaking change</pre><pre># NOT SAFE — changing a type<br>{&quot;name&quot;: &quot;occurred_at&quot;, &quot;type&quot;: &quot;long&quot;}  # was &quot;string&quot; — breaking change</pre><h3>Part 9 — The Tradeoffs (Unvarnished)</h3><h3>Eventual consistency is a product constraint, not an engineering detail</h3><p>When a provider’s specialty is updated and confirmed in the write model, downstream projections lag. Under normal conditions, this is milliseconds. Under load or failure, it can be seconds or longer. If your UI reads from an eventually-consistent projection immediately after a write, it shows the old data.</p><p>This is not a bug you fix. It is a characteristic of the architecture that your product design must accommodate — through optimistic UI updates, explicit “updating…” states, or simply communicating the behaviour to users. It requires product and engineering alignment, not just engineering knowledge.</p><h3>Distributed tracing is non-negotiable, not optional</h3><p>With synchronous HTTP, you trace a request through a request ID in headers. With Kafka, a single enrollment saga might span eight topics and twelve consumer groups over fifteen minutes. Without distributed tracing, debugging is archaeology.</p><p>The minimum viable observability stack for Kafka microservices:</p><ul><li><strong>OpenTelemetry</strong> instrumentation in every producer and consumer</li><li><strong>Correlation ID propagation</strong> through Kafka message headers — every consumer must read it and pass it forward</li><li><strong>A trace aggregator</strong> (Jaeger, Zipkin, Datadog APM) that reconstructs the full flow</li><li><strong>Consumer lag monitoring</strong> per consumer group, per partition — this is your earliest warning of throughput problems</li></ul><h3>The dead-letter queue strategy matters enormously</h3><p>A consumer that throws an unhandled exception will retry indefinitely if you don’t handle it explicitly. This blocks the partition — no messages behind the failing one are processed until the problem is resolved. This is called a <strong>poison pill</strong>.</p><p>Every consumer needs an explicit dead-letter queue strategy:</p><p>python</p><pre>MAX_RETRIES = 3</pre><pre>def consume_with_retry(event, handler_fn, dlq_producer):<br>    attempt = int(event.get(&quot;_retry_count&quot;, 0))<br>    try:<br>        handler_fn(event)<br>    except RetryableError:<br>        if attempt &lt; MAX_RETRIES:<br>            # Re-publish with incremented retry count<br>            event[&quot;_retry_count&quot;] = attempt + 1<br>            producer.publish_to_retry_topic(event, delay_ms=1000 * (2 ** attempt))<br>        else:<br>            dlq_producer.send_to_dlq(event, reason=&quot;max_retries_exceeded&quot;)<br>    except NonRetryableError as e:<br>        dlq_producer.send_to_dlq(event, reason=str(e))</pre><p>DLQ messages need to be <strong>monitored and regularly drained</strong>. A DLQ that fills up and never gets reviewed is just data loss with extra steps.</p><h3>When Kafka is the wrong choice</h3><p><strong>Real-time request-response.</strong> A user submits a form and needs to know within 200ms whether it succeeded. Kafka is not the right tool for that path. Use synchronous HTTP for the response; optionally publish an event as a side-effect.</p><p><strong>Simple two-service notification.</strong> Service A needs to tell Service B about a change, and only Service B will ever care. A webhook or SQS/Pub/Sub message is operationally simpler and almost always sufficient.</p><p><strong>Small teams without operational maturity.</strong> Kafka requires expertise in partition rebalancing, consumer lag management, broker sizing, and schema governance. Introducing it before the team has that maturity produces systems that are harder to reason about than the synchronous alternative. The Strangler Fig pattern — starting with HTTP and migrating to events incrementally — is often the wiser path.</p><p><strong>Strong consistency requirements.</strong> If two services must agree on state before proceeding — a payment authorisation, a prescription dispensing approval — eventual consistency is not acceptable. Kafka does not give you distributed transactions without significant additional engineering (two-phase commit emulation via the Outbox Pattern, or Kafka Streams transactions).</p><h3>Part 10 — Production Checklist</h3><p>Before you call a Kafka-backed microservice production-ready:</p><p><strong>Producer side</strong></p><ul><li>Idempotent producer enabled (enable.idempotence: true)</li><li>Schema registered in Schema Registry with compatibility mode set</li><li>correlation_id propagated in message headers</li><li>Delivery callback handling errors — not fire-and-forget</li><li>flush() called before process exit</li></ul><p><strong>Consumer side</strong></p><ul><li>enable.auto.commit: false — manual offset commit only</li><li>Idempotency check before processing (unique constraint or Redis SET NX)</li><li>Dead-letter queue for unrecoverable failures</li><li>Retry topic with exponential backoff for transient failures</li><li>Graceful shutdown handling (SIGTERM → finish current batch → commit → exit)</li></ul><p><strong>Operational</strong></p><ul><li>Consumer lag alerts per consumer group (threshold: depends on SLA)</li><li>Distributed tracing instrumented end-to-end</li><li>Schema Registry UI accessible to all engineers</li><li>DLQ monitoring dashboard — dead letter accumulation alerting</li><li>Partition count set 2–3x expected peak consumer count (cannot increase without rebalance)</li><li>Replication factor ≥ 3 for all production topics</li><li>Retention period set explicitly — not inherited from broker default</li></ul><h3>The Bottom Line</h3><p>Kafka is not a message queue you swap in for HTTP. It is a fundamentally different communication model that requires deliberate decisions at every layer — partition key selection, consumer group design, schema evolution governance, idempotency strategy, DLQ handling, and distributed tracing.</p><p>The patterns in this article — event sourcing, CQRS, the Saga — each solve a specific class of problem. They are not interchangeable, and they are not automatically solved by adding Kafka. They require engineering discipline that the technology cannot substitute for.</p><p>The teams that operate Kafka reliably are the ones who started with clear answers to: <em>What exactly is Kafka solving here? What new problems does it introduce? And what is the plan for each of them?</em></p><p>The teams that struggle are the ones who adopted it because it was the exciting architecture choice, and discovered six months later that “eventual consistency” requires explanation to a product manager on a Friday afternoon.</p><p>Use Kafka where it earns its place. Understand the tradeoffs deeply enough to explain them to anyone on your team. And build the observability infrastructure before you need it — because with distributed systems, you will need it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T3kkwx72wKpZ-SfC_Bou4A.png" /><figcaption>This will sum all the discussion</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5199ca3b14f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Medallion Architecture in Banking: Building a Scalable Data Reconciliation and Support Framework]]></title>
            <link>https://medium.com/@deveshsharmaanalytics/medallion-architecture-in-banking-building-a-scalable-data-reconciliation-and-support-framework-4ff279675f1a?source=rss-68daf19e5af2------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ff279675f1a</guid>
            <category><![CDATA[medallion-architecture]]></category>
            <category><![CDATA[data-lakehouse]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-lake]]></category>
            <dc:creator><![CDATA[Devesh K Sharma]]></dc:creator>
            <pubDate>Sun, 10 May 2026 02:51:21 GMT</pubDate>
            <atom:updated>2026-05-10T02:57:52.699Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern banking platforms generate enormous volumes of data every second — core banking transactions, payment systems, SWIFT messages, credit card events, loan systems, digital banking APIs, fraud alerts, treasury feeds, and regulatory reports. The challenge is no longer just storing data; it is ensuring that the data is accurate, traceable, reconcilable, and supportable.</p><p>Traditional enterprise data warehouses often struggle with:</p><ul><li>Late-arriving transactions</li><li>Schema changes</li><li>Duplicate records</li><li>Cross-system reconciliation issues</li><li>High operational support effort</li><li>Audit and compliance requirements</li></ul><p>This is where the Medallion Architecture has emerged as one of the most effective modern data engineering patterns for banking platforms.</p><p>Originally popularized in the Lakehouse ecosystem, particularly by <a href="https://www.databricks.com/?utm_source=chatgpt.com">Databricks</a>, the Medallion Architecture organizes data into layered stages:</p><ul><li>Bronze (Raw)</li><li>Silver (Validated and Cleansed)</li><li>Gold (Business-ready)</li></ul><p>The architecture incrementally improves data quality as information flows through each layer.</p><h3>Why Banking Needs Medallion Architecture</h3><p>Banking systems are highly distributed.</p><p>A single customer transaction may pass through:</p><ul><li>Mobile banking</li><li>API gateway</li><li>Fraud engine</li><li>Payment switch</li><li>Core banking</li><li>General ledger</li><li>Regulatory reporting</li><li>Data warehouse</li></ul><p>When reconciliation breaks, operations teams spend hours or even days tracing records across systems.</p><p>The Medallion Architecture solves this problem by:</p><ul><li>Preserving raw immutable data</li><li>Standardizing transformations</li><li>Enforcing auditability</li><li>Supporting replay and recovery</li><li>Simplifying operational support</li><li>Creating deterministic reconciliation pipelines</li></ul><p>In banking, these capabilities are critical for:</p><ul><li>Financial reconciliation</li><li>Regulatory compliance</li><li>Basel reporting</li><li>AML systems</li><li>Payment settlement</li><li>Treasury operations</li><li>Risk analytics</li><li>Customer 360 platforms</li></ul><h3>Understanding the Medallion Architecture</h3><p>The Medallion model is a layered data design pattern where data quality improves progressively from Bronze → Silver → Gold.</p><h3>High-Level Flow</h3><pre>Source Systems<br>       ↓<br>Bronze Layer (Raw Data)<br>       ↓<br>Silver Layer (Validated &amp; Standardized)<br>       ↓<br>Gold Layer (Business Aggregates &amp; Reporting)</pre><h3>Bronze Layer — Raw Immutable Banking Data</h3><p>The Bronze layer stores raw source data exactly as received.</p><p>This includes:</p><ul><li>Core banking extracts</li><li>Kafka transaction streams</li><li>SWIFT files</li><li>CDC events</li><li>Payment gateway logs</li><li>ATM transactions</li><li>Loan servicing feeds</li><li>API payloads</li></ul><p>The Bronze layer is append-only.</p><p>Key principles:</p><ul><li>No business logic</li><li>Minimal transformation</li><li>Preserve source fidelity</li><li>Store ingestion metadata</li><li>Maintain audit trail</li></ul><p>Typical Bronze table columns:</p><p>ColumnDescriptiontransaction_idOriginal transaction IDsource_systemCBS / SWIFT / Card Processoringestion_timestampTime data arrivedbatch_idPipeline execution batchraw_payloadComplete raw JSON/XMLfile_nameSource file referenceload_datePartition column</p><p>According to the official <a href="https://docs.databricks.com/gcp/en/lakehouse/medallion.html?utm_source=chatgpt.com">Databricks documentation</a>, Bronze acts as the “source of truth” for downstream layers.</p><h3>Banking Example — Payment Reconciliation</h3><p>Consider a UPI or ACH payment transaction.</p><p>Data arrives from:</p><ul><li>Payment gateway</li><li>Core banking</li><li>External settlement network</li><li>Merchant processor</li></ul><p>In traditional systems:</p><ul><li>Teams directly transform files</li><li>Intermediate logic becomes opaque</li><li>Replay becomes difficult</li><li>Audit trails are incomplete</li></ul><p>With Medallion:</p><ul><li>Every raw transaction is retained in Bronze</li><li>Any downstream issue can be replayed</li><li>Historical corrections become possible</li><li>Root cause analysis becomes faster</li></ul><p>This dramatically reduces support effort.</p><h3>Silver Layer — Data Validation and Reconciliation Engine</h3><p>The Silver layer is the heart of banking data operations.</p><p>This is where:</p><ul><li>Cleansing occurs</li><li>Duplicates are removed</li><li>Schema validation happens</li><li>Standardization occurs</li><li>Reconciliation logic executes</li></ul><p>Silver transforms unreliable operational feeds into trusted enterprise datasets.</p><p>Typical Silver operations:</p><ul><li>Deduplication</li><li>Null handling</li><li>Currency normalization</li><li>Timestamp standardization</li><li>Account mapping</li><li>Customer matching</li><li>CDC merge handling</li><li>Data quality validations</li></ul><h3>Reconciliation in Silver Layer</h3><p>This is where Medallion Architecture becomes extremely powerful for banking.</p><p>Instead of reconciling reports manually, reconciliation rules become deterministic data pipelines.</p><h3>Example Reconciliation Logic</h3><h3>System A — Payment Gateway</h3><pre>TXN123 → $100</pre><h3>System B — Core Banking</h3><pre>TXN123 → $100</pre><h3>Silver Layer Logic</h3><pre>SELECT<br>    a.transaction_id,<br>    a.amount gateway_amount,<br>    b.amount banking_amount,<br>    CASE<br>        WHEN a.amount = b.amount THEN &#39;MATCHED&#39;<br>        ELSE &#39;MISMATCH&#39;<br>    END reconciliation_status<br>FROM gateway_txns a<br>LEFT JOIN core_banking_txns b<br>ON a.transaction_id = b.transaction_id</pre><p>Result:</p><ul><li>Matched transactions</li><li>Missing records</li><li>Duplicate records</li><li>Amount mismatches</li><li>Settlement breaks</li></ul><p>This creates automated reconciliation pipelines instead of manual Excel-based operations.</p><h3>Why Silver Layer Simplifies Support</h3><p>Banking production support teams constantly face issues like:</p><ul><li>“Why is this transaction missing?”</li><li>“Why did settlement fail?”</li><li>“Why is GL not matching?”</li><li>“Why is reporting delayed?”</li></ul><p>Without layered architecture:</p><ul><li>Teams query raw systems directly</li><li>Logic differs across applications</li><li>Root cause analysis is slow</li></ul><p>With Medallion:</p><ul><li>Bronze provides immutable raw evidence</li><li>Silver provides validated operational truth</li><li>Gold provides business-ready metrics</li></ul><p>Support engineers can isolate issues quickly.</p><p>Example:</p><ul><li>Missing in Bronze → source issue</li><li>Present in Bronze but not Silver → transformation issue</li><li>Present in Silver but not Gold → aggregation/reporting issue</li></ul><p>This layered isolation drastically reduces Mean Time To Resolution (MTTR).</p><h3>Gold Layer — Business and Regulatory Consumption</h3><p>Gold contains curated, business-ready datasets.</p><p>This is where banking executives, auditors, regulators, and BI systems consume data.</p><p>Examples:</p><ul><li>Daily liquidity reports</li><li>Basel exposure calculations</li><li>Customer profitability</li><li>Fraud dashboards</li><li>Treasury exposure</li><li>Regulatory filings</li><li>Financial summaries</li></ul><p>Gold data is:</p><ul><li>Aggregated</li><li>Business-modeled</li><li>Performance optimized</li><li>Governed</li><li>Secure</li></ul><p>Typical Gold tables:</p><ul><li>fact_transactions</li><li>customer_360</li><li>daily_balance_summary</li><li>regulatory_liquidity_report</li><li>fraud_risk_dashboard</li></ul><h3>End-to-End Banking Data Flow</h3><pre>Core Banking / SWIFT / Cards / APIs<br>                ↓<br>        Bronze Layer<br>    (Raw Immutable Storage)<br>                ↓<br>        Silver Layer<br>(Validation + Cleansing + Reconciliation)<br>                ↓<br>          Gold Layer<br> (Reports + BI + Regulatory + AI)</pre><h3>Technologies Commonly Used</h3><h3>Data Ingestion</h3><ul><li>Kafka</li><li>Debezium CDC</li><li>MQ</li><li>API ingestion</li><li>Auto Loader</li></ul><h3>Storage</h3><ul><li>Delta Lake</li><li>Apache Iceberg</li><li>Hudi</li><li>Cloud object storage</li></ul><h3>Processing</h3><ul><li>Apache Spark</li><li>Structured Streaming</li><li>Databricks Workflows</li></ul><h3>Governance</h3><ul><li>Unity Catalog</li><li>Apache Atlas</li><li>Collibra</li></ul><h3>Monitoring</h3><ul><li>Great Expectations</li><li>Monte Carlo</li><li>DataDog</li><li>Splunk</li></ul><p>Delta Lake adds important features like ACID transactions, schema enforcement, time travel, and Change Data Feed support, which are critical for enterprise reconciliation workloads.</p><h3>Key Benefits in Banking</h3><h3>1. Faster Reconciliation</h3><p>Instead of manual operations:</p><ul><li>Reconciliation becomes automated</li><li>Exceptions become visible immediately</li><li>Root cause tracing improves</li></ul><h3>2. Better Auditability</h3><p>Every transaction is preserved in Bronze.</p><p>Auditors can:</p><ul><li>Replay historical loads</li><li>Validate transformations</li><li>Trace lineage end-to-end</li></ul><p>This is critical for:</p><ul><li>SOX</li><li>PCI DSS</li><li>Basel</li><li>AML compliance</li></ul><h3>3. Easier Production Support</h3><p>Layered isolation simplifies debugging.</p><p>Support teams immediately know:</p><ul><li>Source issue</li><li>Transformation issue</li><li>Reporting issue</li></ul><h3>4. Replay and Recovery</h3><p>If a transformation fails:</p><ul><li>Rebuild Silver from Bronze</li><li>Rebuild Gold from Silver</li></ul><p>No dependency on source systems.</p><h3>5. Schema Evolution Support</h3><p>Banking APIs frequently change.</p><p>Medallion architecture handles:</p><ul><li>New columns</li><li>Nested JSON changes</li><li>Evolving schemas</li></ul><p>without breaking downstream consumers.</p><h3>6. Reduced Operational Risk</h3><p>The architecture reduces:</p><ul><li>Hidden transformation logic</li><li>Direct source dependencies</li><li>Manual reconciliation</li><li>Uncontrolled data duplication</li></ul><h3>Real-World Banking Use Cases</h3><h3>Payments Reconciliation</h3><ul><li>ACH</li><li>SWIFT</li><li>RTP</li><li>UPI</li><li>FedNow</li></ul><h3>Fraud Analytics</h3><ul><li>Real-time transaction scoring</li><li>Behavioral anomaly detection</li></ul><h3>Regulatory Reporting</h3><ul><li>Basel III</li><li>CCAR</li><li>AML reporting</li></ul><h3>Customer 360</h3><ul><li>Unified customer profile</li><li>Cross-product analytics</li></ul><h3>Treasury and Liquidity</h3><ul><li>Intraday liquidity</li><li>Cash position reconciliation</li></ul><h3>Best Practices</h3><h3>Keep Bronze Immutable</h3><p>Never update Bronze records.</p><h3>Use CDC Wherever Possible</h3><p>CDC pipelines reduce reconciliation latency.</p><h3>Add Data Quality Checks in Silver</h3><p>Examples:</p><ul><li>Duplicate detection</li><li>Null validation</li><li>Referential integrity</li></ul><h3>Build Domain-Oriented Gold Tables</h3><p>Avoid generic enterprise-wide giant tables.</p><h3>Implement Lineage Tracking</h3><p>Lineage is essential for banking audits.</p><h3>Partition Smartly</h3><p>Typical partitioning:</p><ul><li>load_date</li><li>transaction_date</li><li>region</li><li>source_system</li></ul><h3>Common Mistakes</h3><h3>Overloading Silver with Business Logic</h3><p>Silver should remain operationally clean.</p><h3>Skipping Bronze</h3><p>Direct ingestion to Silver removes replay capability.</p><h3>Excessive Gold Aggregations</h3><p>Over-aggregated Gold tables reduce flexibility.</p><h3>Poor Metadata Management</h3><p>Metadata is essential for support and governance.</p><h3>Medallion Architecture vs Traditional Data Warehouse</h3><p>FeatureTraditional DWHMedallion ArchitectureRaw Data RetentionLimitedFullReplay CapabilityDifficultEasySchema EvolutionHardFlexibleStreaming SupportLimitedNativeReconciliationMostly manualAutomatedAuditabilityModerateStrongSupportabilityComplexLayered and simpleScalabilityExpensiveCloud-native</p><h3>The Future of Banking Data Platforms</h3><p>Modern banks are moving toward:</p><ul><li>Lakehouse architectures</li><li>Real-time reconciliation</li><li>Streaming analytics</li><li>AI-driven risk systems</li><li>Event-driven data platforms</li></ul><p>Medallion Architecture has become the foundational pattern enabling this transition.</p><p>It is not merely a storage strategy; it is an operational model that improves:</p><ul><li>Reliability</li><li>Governance</li><li>Reconciliation</li><li>Auditability</li><li>Production support</li><li>Scalability</li></ul><p>Community discussions among data engineers also emphasize that Medallion Architecture is valuable because it separates raw, validated, and business-ready datasets into clearly governed layers, making support and reporting significantly easier.</p><p>In Infographics: —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9M4o9rkPrtqFevy0LEFExg.png" /></figure><h3>Conclusion</h3><p>Banking systems demand accuracy, traceability, and operational resilience.</p><p>The Medallion Architecture provides a practical and scalable way to achieve these goals by organizing data into progressive quality layers:</p><ul><li>Bronze for raw immutable data</li><li>Silver for validation and reconciliation</li><li>Gold for business consumption</li></ul><p>For banking organizations, the biggest advantage is not just analytics — it is operational simplicity.</p><p>By separating ingestion, reconciliation, and reporting into distinct layers, banks can:</p><ul><li>Reduce reconciliation failures</li><li>Simplify production support</li><li>Improve audit readiness</li><li>Enable real-time analytics</li><li>Scale data platforms efficiently</li></ul><p>As financial institutions continue modernizing toward cloud-native lakehouse platforms, Medallion Architecture is rapidly becoming the standard blueprint for enterprise banking data engineering.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ff279675f1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>