<?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 YOUSSEF EL MESSBAHI on Medium]]></title>
        <description><![CDATA[Stories by YOUSSEF EL MESSBAHI on Medium]]></description>
        <link>https://medium.com/@youssefelmessbahi?source=rss-573653523742------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*teSNQ7N5wU2Nj1ix</url>
            <title>Stories by YOUSSEF EL MESSBAHI on Medium</title>
            <link>https://medium.com/@youssefelmessbahi?source=rss-573653523742------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 17:06:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@youssefelmessbahi/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[Inside the Kafka Consumer: How Records Are Fetched, Processed, and Committed Part 2]]></title>
            <link>https://medium.com/@youssefelmessbahi/inside-the-kafka-consumer-how-records-are-fetched-processed-and-committed-part-2-b28a76fd46e2?source=rss-573653523742------2</link>
            <guid isPermaLink="false">https://medium.com/p/b28a76fd46e2</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[kafka-consumer]]></category>
            <dc:creator><![CDATA[YOUSSEF EL MESSBAHI]]></dc:creator>
            <pubDate>Fri, 20 Nov 2026 23:05:16 GMT</pubDate>
            <atom:updated>2026-11-20T23:05:16.353Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exception handling and dead-letter topics, multiple topics and JSON type mapping, concurrency, partition assignment strategies, and rebalancing.</h3><p>In Part 1, we followed a record through the consumer when everything goes well: the listener container, the poll loop, the group coordinator, offset lookup, the fetch path, and the commit strategies that decide whether a crash loses or repeats events.</p><p>That consumer lived in an ideal world. Every record was valid JSON, every listener call succeeded, and a single consumer read a single topic:</p><pre>order-consumer-group<br>    └── 1 consumer  →  order-events (P0, P1, P2)</pre><p>Production is less kind. Sooner or later, these questions appear:</p><ul><li>What happens when a record cannot be deserialized, or when our listener throws an exception?</li><li>What if one consumer must read more than one topic, each with its own event type?</li><li>What if several consumers in one application read different topics?</li><li>What if several consumers must share the partitions of the same topic?</li><li>Who decides which consumer gets which partition, and what happens when a consumer joins, leaves, or crashes?</li></ul><p>In this article, we will answer each of them. We start with failures, because a single bad record can stop a consumer forever. Then we look at multiple topics and the JSON type mechanism where many setups quietly break, and finish with scaling: concurrency, the four partition assignment strategies, and eager versus cooperative rebalancing.</p><h3>8. When Things Go Wrong: Exception Handling</h3><p>Let us look at the consumer flow again, this time asking where an exception can be thrown:</p><pre>poll()<br>    ↓<br>deserialize each record      ← 1st place: key or value cannot be deserialized<br>    ↓<br>invoke the listener          ← 2nd place: our business logic throws<br>    ↓<br>commit offset</pre><p>These two places look similar, but they fail in completely different ways. A deserialization failure happens inside the Kafka client, before Spring or our code ever sees the record. A processing failure happens inside our listener, where Spring is in control.</p><p>We start with the first one, because its default behavior is the most dangerous.</p><h4>Deserialization failure: the infinite loop</h4><p>Our consumer expects JSON values. Suppose a misconfigured producer publishes a plain String to order-events:</p><pre>order-events-0<br>    offset 0 → {&quot;orderId&quot;:&quot;ORD-1&quot;,&quot;status&quot;:&quot;CREATED&quot;}    valid JSON<br>    offset 1 → {&quot;orderId&quot;:&quot;ORD-2&quot;,&quot;status&quot;:&quot;CREATED&quot;}    valid JSON<br>    offset 2 → hello                                     not JSON</pre><p>The consumer processes offsets 0 and 1 normally. Then poll() fetches offset 2, and JsonDeserializer throws.</p><p>Because the exception is thrown inside poll(), no record reaches the listener and no offset is committed. The consumer&#39;s position stays at 2. The next poll() fetches offset 2 again, fails again, and so on:</p><pre>poll() → fetch offset 2 → deserialization error → log stack trace<br>poll() → fetch offset 2 → deserialization error → log stack trace<br>poll() → fetch offset 2 → deserialization error → log stack trace<br>...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DAnGg8xPn0rvza2HGebJCQ.png" /></figure><p>The logs fill with the same stack trace, and the partition stops moving. The group status shows it clearly:</p><pre>kafka-consumer-groups.sh --bootstrap-server localhost:9092 \<br>  --describe --group order-consumer-group</pre><pre>TOPIC         PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG<br>order-events  0          2               3               1</pre><p>CURRENT-OFFSET is 2: the next record the group will read. LOG-END-OFFSET is 3: the partition holds three records. One record is left, and it will never be consumed.</p><p>Restarting the consumer does not help. The committed offset is still 2, so the new instance starts at offset 2 and falls into the same loop. Every record produced after it is blocked too. This is the classic <strong>poison pill</strong>.</p><h4>The fix: wrap the deserializer</h4><p>The root problem is that the exception happens in a place where nobody can handle it. Spring Kafka’s ErrorHandlingDeserializer moves it to a place where somebody can.</p><p>It is a wrapper. We configure it as the deserializer, and tell it which real deserializer to delegate to:</p><pre># Use the wrapper as the deserializer<br>spring.kafka.consumer.key-deserializer=\<br>org.springframework.kafka.support.serializer.ErrorHandlingDeserializer<br>spring.kafka.consumer.value-deserializer=\<br>org.springframework.kafka.support.serializer.ErrorHandlingDeserializer</pre><pre># The real deserializers, called by the wrapper<br>spring.kafka.consumer.properties.spring.deserializer.key.delegate.class=\<br>org.apache.kafka.common.serialization.StringDeserializer<br>spring.kafka.consumer.properties.spring.deserializer.value.delegate.class=\<br>org.springframework.kafka.support.serializer.JsonDeserializer</pre><p>When the delegate succeeds, the wrapper returns its result unchanged. When it fails, the wrapper catches the exception instead of letting it escape from poll():</p><pre>Raw key bytes / raw value bytes<br>    ↓<br>ErrorHandlingDeserializer<br>    ↓<br>Delegate (JsonDeserializer) throws?<br>    ├── no  → return the Order object → listener<br>    └── yes → return null + store the failure in a header<br>                ↓<br>              container sees the failure → error handler</pre><p>The record now reaches the listener container like any other record, carrying the information that it failed. The container does not call our listener with it; it hands it to the <strong>error handler</strong>.</p><h4>What the default error handler does</h4><p>Without any extra configuration, Spring Kafka uses a DefaultErrorHandler. For a deserialization failure, its behavior is:</p><ul><li><strong>No retry.</strong> A DeserializationException is classified as fatal: the bytes will not become valid JSON by trying again.</li><li><strong>Log the error.</strong></li><li><strong>Commit the offset</strong> and move on to the next record.</li></ul><p>The loop is gone. The group status now shows LAG 0: the consumer has moved past offset 2.</p><p>But look at what that means: the record is gone too. It was skipped, logged, and committed. If it was a real order sent in a wrong format, nobody will ever process it, and the only trace is a log line.</p><p>The default handler is a safe starting point, not a production strategy. In production, a failed record should be <strong>kept</strong> somewhere, so that after the bug is fixed it can be inspected, repaired, and replayed. That is what retries and dead-letter topics are for.</p><h4>Retrying with back-off</h4><p>We replace the default handler with our own DefaultErrorHandler bean, which Spring Boot automatically plugs into the listener container factory. The first decision is the retry policy, expressed as a <strong>back-off</strong>.</p><p><strong>FixedBackOff</strong> waits the same time between every attempt:</p><pre>@Bean<br>public DefaultErrorHandler errorHandler() {<br>    // wait 1 second between attempts, retry at most 2 times<br>    return new DefaultErrorHandler(new FixedBackOff(1000L, 2));<br>}</pre><pre>Attempt 1            → fail<br>  wait 1 s<br>Attempt 2 (retry 1)  → fail<br>  wait 1 s<br>Attempt 3 (retry 2)  → fail → give up</pre><p><strong>ExponentialBackOffWithMaxRetries</strong> doubles the wait after each failure, up to a ceiling:</p><pre>@Bean<br>public DefaultErrorHandler errorHandler() {<br>    ExponentialBackOffWithMaxRetries backOff = new ExponentialBackOffWithMaxRetries(5);<br>    backOff.setInitialInterval(1000L);  // first retry after 1 s<br>    backOff.setMultiplier(2.0);         // double the wait each time<br>    backOff.setMaxInterval(10000L);     // never wait more than 10 s<br>    return new DefaultErrorHandler(backOff);<br>}</pre><pre>Retry 1 → after 1 s<br>Retry 2 → after 2 s<br>Retry 3 → after 4 s<br>Retry 4 → after 8 s<br>Retry 5 → after 10 s   (16 s capped at the 10 s maximum)<br>→ give up</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8v189zEl9EYqr48fwLHh7A.jpeg" /></figure><p>Exponential back-off suits temporary problems, such as a database that is restarting or a downstream API that is rate-limiting: early retries are fast, and later ones give the dependency time to recover.</p><p>Two things to keep in mind. First, these retries are <strong>blocking</strong>: the error handler re-seeks the partition to the failed record, so while it retries, no later record of that partition is processed. Ordering is preserved, but the partition is paused. Second, the retries run on the consumer thread, so the total back-off must stay well below max.poll.interval.ms from Part 1. Otherwise, the consumer is removed from the group in the middle of its own retries.</p><h4>When retries are exhausted: the recoverer</h4><p>Retrying is only half of the policy. The other half is what happens after the last attempt fails. That is the job of a <strong>recoverer</strong>.</p><p>A recoverer is a ConsumerRecordRecoverer, a functional interface that receives the failed record and the exception:</p><pre>void accept(ConsumerRecord&lt;?, ?&gt; record, Exception exception);</pre><p>DefaultErrorHandler has a constructor that takes both a recoverer and a back-off:</p><pre>public DefaultErrorHandler(ConsumerRecordRecoverer recoverer, BackOff backOff)</pre><h4>Dead-letter topics</h4><p>The most common recoverer is DeadLetterPublishingRecoverer, provided by Spring Kafka. Its accept() method publishes the failed record to a <strong>dead-letter topic</strong> (DLT): a separate topic that holds every record the consumer could not handle.</p><p>First, we create the DLT. By default, the recoverer sends a failed record to &lt;original-topic&gt;-dlt, <strong>into the same partition number</strong> as the original record. So the DLT needs at least as many partitions as the source topic:</p><pre>@Bean<br>public NewTopic orderEventsDlt() {<br>    return TopicBuilder.name(&quot;order-events-dlt&quot;)<br>            .partitions(3)   // same as order-events<br>            .build();<br>}</pre><p>Then we wire the recoverer into the error handler. The recoverer needs a KafkaTemplate to publish with, and Spring Boot builds one from the spring.kafka.producer.* properties:</p><pre>@Bean<br>public DeadLetterPublishingRecoverer deadLetterPublishingRecoverer(<br>        KafkaTemplate&lt;Object, Object&gt; template) {<br>    return new DeadLetterPublishingRecoverer(template);<br>}</pre><pre>@Bean<br>public DefaultErrorHandler errorHandler(DeadLetterPublishingRecoverer recoverer) {<br>    return new DefaultErrorHandler(recoverer, new FixedBackOff(1000L, 2));<br>}</pre><p>The error handler now has both features: it retries according to the back-off, and when the retries are exhausted, it calls the recoverer, which publishes the record to order-events-dlt. The offset is then committed and the consumer moves on, but this time nothing is lost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U3bMLSaCk7wERcRWK5GoOw.jpeg" /></figure><h4>How the DLT works internally</h4><p>For a deserialization failure, there is a puzzle. The recoverer must publish the failed record, but the record could not be turned into an object. What is there to publish?</p><p>The answer is in what the wrapper did. When the delegate failed, ErrorHandlingDeserializer created a DeserializationException holding the full error details <em>and the original raw bytes</em>. It then built the ConsumerRecord like this:</p><ul><li>the part that failed (key or value) is set to null,</li><li>the exception, with the raw bytes, is stored in a record header: springDeserializerExceptionValue for a failed value, springDeserializerExceptionKey for a failed key.</li></ul><pre>Example 1: value deserialization failed<br>    key    = &quot;O-111&quot;<br>    value  = null<br>    header springDeserializerExceptionValue = raw value bytes</pre><pre>Example 2: key deserialization failed<br>    key    = null<br>    value  = Order object<br>    header springDeserializerExceptionKey = raw key bytes</pre><p>Conceptually, the recoverer’s accept() rebuilds the record from these pieces: whatever was deserialized successfully is used as-is, and whatever failed is replaced by its raw bytes:</p><pre>public void accept(ConsumerRecord&lt;?, ?&gt; record, Exception exception) {<br>    // 1. raw bytes of whatever failed, taken from the exception header<br>    byte[] rawKey   = /* springDeserializerExceptionKey   */;<br>    byte[] rawValue = /* springDeserializerExceptionValue */;</pre><pre>    // 2. a new record for the DLT, same partition as the original<br>    ProducerRecord&lt;Object, Object&gt; dltRecord = new ProducerRecord&lt;&gt;(<br>        record.topic() + &quot;-dlt&quot;,<br>        record.partition(),<br>        record.key()   != null ? record.key()   : rawKey,<br>        record.value() != null ? record.value() : rawValue);</pre><pre>    // 3. publish it<br>    kafkaTemplate.send(dltRecord);<br>}</pre><p>The real implementation also adds diagnostic headers to the DLT record, such as kafka_dlt-original-topic, kafka_dlt-original-partition, kafka_dlt-original-offset, and kafka_dlt-exception-message. Whoever investigates the DLT later knows exactly where each record came from and why it failed.</p><h4>The serializer puzzle</h4><p>This raises a practical question: which serializers should the DLT’s KafkaTemplate use? The record it publishes can contain raw bytes, objects, or both:</p><pre>Value failed  → key &quot;O-111&quot; (String), value byte[]<br>Key failed    → key byte[],           value Order object</pre><p>In most applications the key is a String, and String keys almost never fail to deserialize. Deserialization problems come from the value, usually from JSON. In that case, the failed value is always published as raw bytes, and this producer configuration is enough:</p><pre>spring.kafka.producer.key-serializer=\<br>org.apache.kafka.common.serialization.StringSerializer<br>spring.kafka.producer.value-serializer=\<br>org.apache.kafka.common.serialization.ByteArraySerializer</pre><p>When the key is also an object, either side can fail, or both. One robust solution is to override how the recoverer builds the outgoing record, and always convert both key and value to bytes. Then a single serializer handles every case:</p><pre>spring.kafka.producer.key-serializer=\<br>org.apache.kafka.common.serialization.ByteArraySerializer<br>spring.kafka.producer.value-serializer=\<br>org.apache.kafka.common.serialization.ByteArraySerializer</pre><pre>@Bean<br>public DeadLetterPublishingRecoverer deadLetterPublishingRecoverer(<br>        KafkaTemplate&lt;Object, Object&gt; template, ObjectMapper objectMapper) {</pre><pre>    return new DeadLetterPublishingRecoverer(template) {<br>        @Override<br>        protected ProducerRecord&lt;Object, Object&gt; createProducerRecord(<br>                ConsumerRecord&lt;?, ?&gt; record, TopicPartition tp,<br>                Headers headers, byte[] key, byte[] value) {</pre><pre>            // key/value are the raw bytes when that part failed, otherwise null<br>            Object finalKey   = key   != null ? key   : toBytes(objectMapper, record.key());<br>            Object finalValue = value != null ? value : toBytes(objectMapper, record.value());<br>            return new ProducerRecord&lt;&gt;(tp.topic(), tp.partition(), finalKey, finalValue, headers);<br>        }<br>    };<br>}</pre><pre>private static byte[] toBytes(ObjectMapper mapper, Object data) {<br>    try {<br>        return data == null ? null : mapper.writeValueAsBytes(data);<br>    } catch (JsonProcessingException e) {<br>        throw new IllegalStateException(&quot;Cannot serialize record for DLT&quot;, e);<br>    }<br>}</pre><p>Spring Kafka also offers DelegatingByTypeSerializer, which picks a serializer per Java type, for example ByteArraySerializer for byte[] and JsonSerializer for Order. Either approach works; the important point is that the DLT template must be able to serialize both shapes.</p><h4>Custom recoverers</h4><p>A recoverer does not have to publish to Kafka. Because ConsumerRecordRecoverer is a functional interface, any logic fits: storing the failed record in a database table, sending an alert, or both:</p><pre>@Bean<br>public DefaultErrorHandler errorHandler(FailedEventRepository repository) {<br>    return new DefaultErrorHandler(<br>        (record, exception) -&gt; {<br>            repository.save(FailedEvent.from(record, exception));<br>            alerting.notify(&quot;Order event failed: &quot; + exception.getMessage());<br>        },<br>        new FixedBackOff(1000L, 2));<br>}</pre><h4>Processing failure: when the listener throws</h4><p>Now the second place. The record deserializes correctly, but our business logic throws, for example a NullPointerException because an expected field is missing.</p><p>This time no wrapper is needed. The exception is thrown inside the listener, where the container is already in control, so the DefaultErrorHandler applies automatically. Its default behavior for a processing failure is:</p><ul><li>retry the record up to 9 more times, with no delay (10 attempts in total),</li><li>then log the error,</li><li>commit the offset and continue with the next record.</li></ul><p>Everything we built for deserialization applies unchanged: the same back-off policies, the same recoverer, the same DLT.</p><p>One refinement matters here. Not every exception deserves a retry. A NullPointerException caused by bad data will fail ten times in a row; a timeout from a downstream service may succeed on the next attempt. The error handler can be told which exceptions to skip straight to the recoverer:</p><pre>DefaultErrorHandler handler = new DefaultErrorHandler(recoverer, backOff);<br>handler.addNotRetryableExceptions(NullPointerException.class,<br>                                  IllegalArgumentException.class);</pre><p>And because a retried record is processed again, the listener should be idempotent, exactly as we concluded for duplicates in Part 1.</p><p><strong>Key concept</strong></p><p>A deserialization failure happens inside the Kafka client and loops forever unless ErrorHandlingDeserializer hands it to the error handler. A processing failure reaches the error handler automatically. In both cases, the default handler eventually skips the record; in production, a back-off plus a recoverer, usually a dead-letter topic, ensures failed records are retried and then kept, never silently lost.</p><p><strong>Section 8 takeaway</strong></p><p>Our consumer can now survive bad records. Next, we make it read more than one kind of record.</p><h3>9. One Consumer, Many Topics: Manual Mapping</h3><p>Suppose our consumer must now handle payments as well as orders. Payments are published to a separate topic, payment-events.</p><p>@KafkaListener accepts a list of topics:</p><pre>@KafkaListener(topics = {&quot;order-events&quot;, &quot;payment-events&quot;})</pre><p>It also accepts a regular expression, which subscribes to every matching topic, including topics created later:</p><pre>@KafkaListener(topicPattern = &quot;.*-events&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l3nXWEZYiZiscx87nTyTqg.jpeg" /></figure><h4>What the consumer receives</h4><p>If this consumer is alone in its group, it is assigned every partition of both topics. Each poll() can return records from any of them, mixed in one batch:</p><pre>poll() returns:<br>    order-events-0    offset 42   OrderCreated<br>    payment-events-1  offset 17   PaymentAuthorized<br>    order-events-2    offset 77   OrderShipped<br>    payment-events-0  offset 9    PaymentCaptured</pre><p>Ordering is still guaranteed only within each partition, exactly as in the producer series. There is no ordering between the two topics, and no ordering between partitions of the same topic.</p><h4>The problem: one value deserializer</h4><p>Order records must become Order objects. Payment records must become Payment objects. But the consumer has exactly one value deserializer, configured once, for every record it reads.</p><p>The deserializer does not choose based on the topic. So how does each record end up as the right class?</p><p>The first approach is to stop asking Kafka for objects and take control of the conversion ourselves.</p><h4>Approach 1: read Strings, map them in the listener</h4><p>We configure the value deserializer to return the raw JSON text:</p><pre>spring.kafka.consumer.group-id=order-consumer-group<br>spring.kafka.consumer.key-deserializer=\<br>org.apache.kafka.common.serialization.StringDeserializer</pre><pre># Receive raw JSON text; the listener decides the target class<br>spring.kafka.consumer.value-deserializer=\<br>org.apache.kafka.common.serialization.StringDeserializer</pre><p>The listener receives the complete ConsumerRecord, which carries the topic name next to the value, and chooses the class from it:</p><pre>@Component<br>public class EventListener {</pre><pre>    private final ObjectMapper objectMapper;</pre><pre>    public EventListener(ObjectMapper objectMapper) {<br>        this.objectMapper = objectMapper;<br>    }</pre><pre>    @KafkaListener(topics = {&quot;order-events&quot;, &quot;payment-events&quot;})<br>    public void consume(ConsumerRecord&lt;String, String&gt; record) throws Exception {</pre><pre>        switch (record.topic()) {<br>            case &quot;order-events&quot; -&gt; {<br>                Order order = objectMapper.readValue(record.value(), Order.class);<br>                // business logic for orders<br>            }<br>            case &quot;payment-events&quot; -&gt; {<br>                Payment payment = objectMapper.readValue(record.value(), Payment.class);<br>                // business logic for payments<br>            }<br>            default -&gt; throw new IllegalStateException(&quot;Unexpected topic &quot; + record.topic());<br>        }<br>    }<br>}</pre><p>We inject Spring Boot’s ObjectMapper instead of creating a new one. It is thread-safe, expensive to build, and already configured with the application&#39;s JSON settings.</p><h4>What this approach gives and costs</h4><p>It is explicit. Anyone reading the listener sees exactly which topic produces which class. It also works with any producer, including services written in other languages, because it relies on nothing but the topic name.</p><p>The cost is that deserialization now lives in business code. Every new event type means another branch. And a malformed record no longer fails inside the deserializer; it fails inside our listener, as a Jackson exception, where the container’s error handler treats it like any other processing failure.</p><p><strong>Key concept</strong></p><p>A consumer can subscribe to many topics, but it has one value deserializer. With StringDeserializer, the application takes over the job of mapping each record to its class.</p><p><strong>Section 9 takeaway</strong></p><p>Manual mapping is simple and explicit. To let Spring do the mapping instead, we first need to understand how JsonDeserializer chooses a type, because it does not look at the topic at all.</p><h3>10. The JSON Type Flow: How the Consumer Chooses a Class</h3><p>JSON carries field names and values, but no Java type. When JsonDeserializer receives:</p><pre>{ &quot;orderId&quot;: &quot;ORD-1001&quot;, &quot;totalAmount&quot;: 99.99, &quot;status&quot;: &quot;CREATED&quot; }</pre><p>it has to find the target class somewhere else. There are two possible sources: information the producer attached to the record, or the consumer’s own configuration.</p><h4>At the producer side: the __TypeId__ header</h4><p>Since Kafka 0.11, every record can carry <strong>headers</strong>: small key-value pairs stored next to the key and value. They are metadata about the record, not part of the business payload.</p><p>When the producer uses Spring’s JsonSerializer, this property is true by default:</p><pre>spring.kafka.producer.properties.spring.json.add.type.headers=true</pre><p>With it, the serializer writes a header named __TypeId__ containing the class of the object it serialized:</p><pre>Record<br>├── key:     &quot;ORD-1001&quot;<br>├── value:   {&quot;orderId&quot;:&quot;ORD-1001&quot;,&quot;totalAmount&quot;:99.99,...}<br>└── headers:<br>        __TypeId__ = com.eda.producer.model.Order</pre><p>We can see these headers directly with the console consumer:</p><pre>kafka-console-consumer.sh --bootstrap-server localhost:9092 \<br>  --topic order-events --from-beginning \<br>  --property print.headers=true</pre><pre>__TypeId__:com.eda.producer.model.Order   {&quot;orderId&quot;:&quot;ORD-1001&quot;,...}</pre><p>Two details matter here.</p><p>First, the header names the <strong>producer’s</strong> class. The consumer usually has its own Order class in another package, such as com.eda.consumer.model.Order. The header alone is not enough to build the consumer&#39;s object.</p><p>Second, the header is not guaranteed. A producer written in Python or Go, a Spring producer with the property disabled, or a producer using a different serializer will send records without it. Before relying on the header, check that the producer really sends it.</p><h4>At the consumer side: the decision flow</h4><p>JsonDeserializer follows a fixed sequence of questions for every record:</p><pre>Record arrives (bytes + headers)<br>    ↓<br>spring.json.use.type.headers = true?  (default: true)<br>    │<br>    ├── false → use spring.json.value.default.type<br>    │<br>    └── true → Is __TypeId__ present?<br>            │<br>            ├── no  → use spring.json.value.default.type<br>            │<br>            └── yes → Is spring.json.type.mapping configured for it?<br>                    │<br>                    ├── yes → use the mapped consumer class<br>                    │<br>                    └── no  → load the class named in the header<br>                            ├── package not trusted   → IllegalArgumentException<br>                            ├── class not on classpath → ClassNotFoundException<br>                            └── otherwise              → deserialize</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W5UrcLwstCcugVTXWnSXNw.jpeg" /></figure><p>Read it from the top. If the consumer is allowed to use headers, and a header is present, the header wins. A configured mapping translates the producer’s class into the consumer’s class. Without a mapping, the deserializer tries to load the producer’s class name directly, which works only if the consumer has that exact class and trusts its package. The value.default.type we configured in Part 1 is only the fallback for records that carry no usable header.</p><p>This explains a confusing situation. In Part 1, our single-topic consumer worked with only value.default.type. If the producer sends a header and the consumer has no mapping, that same configuration can suddenly fail with an untrusted-package error or a ClassNotFoundException, because the header takes priority over the default.</p><h4>Why trusted packages exist</h4><p>The trusted-packages check is a security measure. Without it, whoever writes to the topic could name <em>any</em> class in the header, and the consumer would try to instantiate it. Deserializing attacker-chosen classes is a well-known source of security vulnerabilities in Java.</p><p>By default, only java.util and java.lang are trusted. When a consumer really must load classes named in headers, it lists its own packages:</p><pre>spring.kafka.consumer.properties.spring.json.trusted.packages=com.eda.consumer.model</pre><p>Avoid spring.json.trusted.packages=* outside local experiments. It switches the protection off.</p><p><strong>Key concept</strong></p><p>__TypeId__ says what the producer sent. spring.json.type.mapping translates it into what the consumer should build. value.default.type is only the fallback when there is no header to use.</p><p><strong>Section 10 takeaway</strong></p><p>With this flow in mind, automatic mapping for several topics becomes a configuration problem rather than a code problem.</p><h3>11. One Consumer, Many Topics: Automatic Type Mapping</h3><p>Now we let JsonDeserializer do the work.</p><p>The producer sends both event types through one template typed with Object, so each record&#39;s __TypeId__ header carries its own class:</p><pre>@Service<br>public class ProducerService {</pre><pre>    private final KafkaTemplate&lt;String, Object&gt; kafkaTemplate;</pre><pre>    public ProducerService(KafkaTemplate&lt;String, Object&gt; kafkaTemplate) {<br>        this.kafkaTemplate = kafkaTemplate;<br>    }</pre><pre>    public void sendOrder(Order order) {<br>        kafkaTemplate.send(&quot;order-events&quot;, order.getOrderId(), order);<br>    }</pre><pre>    public void sendPayment(Payment payment) {<br>        kafkaTemplate.send(&quot;payment-events&quot;, payment.getPaymentId(), payment);<br>    }<br>}</pre><p>The consumer maps each producer class to its own class:</p><pre>spring.kafka.consumer.value-deserializer=\<br>org.springframework.kafka.support.serializer.JsonDeserializer</pre><pre># producer class : consumer class<br>spring.kafka.consumer.properties.spring.json.type.mapping=\<br>com.eda.producer.model.Order:com.eda.consumer.model.Order,\<br>com.eda.producer.model.Payment:com.eda.consumer.model.Payment</pre><pre># Fallback when a record has no __TypeId__ header<br>spring.kafka.consumer.properties.spring.json.value.default.type=\<br>com.eda.consumer.model.Order</pre><p>The consumer’s classes are ordinary POJOs that only need matching field names:</p><pre>package com.eda.consumer.model;</pre><pre>public class Payment {<br>    private String paymentId;<br>    private String customerId;<br>    private Double totalAmount;<br>    private String status;<br>    // getters and setters<br>}</pre><p>The listener no longer parses anything. The value already arrives as the right object, so the record is typed with Object, not String:</p><pre>@KafkaListener(topics = {&quot;order-events&quot;, &quot;payment-events&quot;})<br>public void consume(ConsumerRecord&lt;String, Object&gt; record) {</pre><pre>    if (record.value() instanceof Order order) {<br>        // business logic for orders<br>    } else if (record.value() instanceof Payment payment) {<br>        // business logic for payments<br>    }<br>}</pre><h4>A cleaner listener with @KafkaHandler</h4><p>Spring Kafka can also do the dispatching for us. When @KafkaListener is placed on the class, each method annotated with @KafkaHandler receives the payload type it declares:</p><pre>@Component<br>@KafkaListener(topics = {&quot;order-events&quot;, &quot;payment-events&quot;})<br>public class EventListener {</pre><pre>    @KafkaHandler<br>    public void onOrder(Order order) {<br>        // business logic for orders<br>    }</pre><pre>    @KafkaHandler<br>    public void onPayment(Payment payment) {<br>        // business logic for payments<br>    }</pre><pre>    @KafkaHandler(isDefault = true)<br>    public void onUnknown(Object event) {<br>        // log events this service does not handle<br>    }<br>}</pre><p>Adding a new event type now means adding a mapping entry and one method, without touching the existing handlers.</p><h4>Map logical names, not class names</h4><p>Mapping full class names still couples the consumer to the producer’s package structure. If the producer moves Order to another package, every consumer mapping breaks.</p><p>A cleaner contract uses short logical names, called tokens, on <strong>both</strong> sides. The producer maps its class to a token, and the header carries the token instead of the class name:</p><pre># Producer<br>spring.kafka.producer.properties.spring.json.type.mapping=\<br>order:com.eda.producer.model.Order,\<br>payment:com.eda.producer.model.Payment</pre><pre># Consumer<br>spring.kafka.consumer.properties.spring.json.type.mapping=\<br>order:com.eda.consumer.model.Order,\<br>payment:com.eda.consumer.model.Payment</pre><pre>__TypeId__ = order</pre><p>Each service now maps order to its own class. Either side can rename or move classes freely, as long as the token stays the same. The token becomes part of the event contract, just like the topic name and the JSON fields.</p><p><strong>Key concept</strong></p><p>With a type header and a type mapping, one consumer can read several topics and receive the right class for each record, with no parsing code in the listener.</p><p><strong>Section 11 takeaway</strong></p><p>One listener can serve several topics. Often, though, we want separate listeners, one per event type, each with its own logic and its own failure handling.</p><h3>12. Several Consumers, Different Topics, One Application</h3><h4>Approach 1: separate applications</h4><p>The simplest option is to deploy two applications, one for orders and one for payments. Each runs the basic setup from Part 1, with one consumer and one configuration.</p><p>This always works, and it brings real benefits: each service can be deployed, scaled, and restarted independently. The cost is operational: two services to build, monitor, and maintain.</p><h4>Approach 2: two listeners in one application</h4><p>Inside a single application, we can declare two listener methods:</p><pre>@Component<br>public class EventListener {</pre><pre>    @KafkaListener(topics = &quot;order-events&quot;)<br>    public void consumeOrder(Order order) {<br>        System.out.println(&quot;Received: &quot; + order.getOrderId());<br>    }</pre><pre>    @KafkaListener(topics = &quot;payment-events&quot;)<br>    public void consumePayment(Payment payment) {<br>        System.out.println(&quot;Received: &quot; + payment.getPaymentId());<br>    }<br>}</pre><p>Remember Section 2 of Part 1: each @KafkaListener gets its own listener container, its own KafkaConsumer, and its own thread. A slow payment never blocks the next order.</p><p>Both consumers use the group-id from application.properties, so they are members of the same group. That works, but it couples them: if the payment consumer triggers a rebalance, for example by exceeding max.poll.interval.ms, the order consumer takes part in that rebalance too. Giving each listener its own group keeps them independent:</p><pre>@KafkaListener(topics = &quot;payment-events&quot;, groupId = &quot;payment-consumer-group&quot;)</pre><h4>With type headers and mapping: it works</h4><p>Using the mapping configuration from Section 11, each record’s __TypeId__ header is translated into the right class. Order records become Order, payment records become Payment, and each listener receives exactly what it declares. This is the recommended setup when the producer sends type headers.</p><h4>With type headers disabled: it breaks</h4><p>Now suppose the producer is not a Spring application, or we decide to ignore headers and rely on the default type:</p><pre>spring.kafka.consumer.properties.spring.json.use.type.headers=false<br>spring.kafka.consumer.properties.spring.json.value.default.type=\<br>com.eda.consumer.model.Order</pre><p>Order events still work. Then a payment event arrives, and the flow from Section 10 is followed exactly:</p><ol><li>The payment consumer fetches the record.</li><li>Headers are ignored, because use.type.headers=false.</li><li>The deserializer falls back to the default type, Order.</li><li>The payment JSON is deserialized into an Order object. Fields that do not exist on Order are dropped, and missing ones stay null.</li><li>Spring tries to pass that Order to a method that expects a Payment.</li></ol><pre>MessageConversionException: Cannot convert from<br>[com.eda.consumer.model.Order] to [com.eda.consumer.model.Payment]<br>for GenericMessage [payload=Order(orderId=null, customerId=CUST-2,<br>productId=null, quantity=null, totalAmount=99.99, status=CREATED)]</pre><p>The payload in that message tells the story: an Order with no order id, built from a payment&#39;s fields.</p><h4>Why it breaks: one ConsumerFactory</h4><p>Remember Section 2 of Part 1: Spring Boot creates <strong>one</strong> ConsumerFactory from application.properties, and every listener container gets its KafkaConsumer from it.</p><pre>application.properties<br>    ↓<br>One ConsumerFactory  (default type = Order)<br>    ├── KafkaConsumer for order-events    → default type Order ✓<br>    └── KafkaConsumer for payment-events  → default type Order ✗</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qWvazKWnjOADmcXezP469g.jpeg" /></figure><p>Both consumers inherit the same default type. Two listeners, one recipe. Once we see that, the fix is clear: each event type needs its own configuration.</p><h4>The quick fix: override per listener</h4><p>@KafkaListener accepts a properties attribute that overrides consumer properties for that listener only:</p><pre>@KafkaListener(<br>    topics = &quot;payment-events&quot;,<br>    properties = &quot;spring.json.value.default.type=com.eda.consumer.model.Payment&quot;)<br>public void consumePayment(Payment payment) { ... }</pre><p>For one or two listeners, this is often enough.</p><h4>The structured fix: one factory per event type</h4><p>When each listener needs more than one different setting, separate factories keep the configuration explicit:</p><pre>@Configuration<br>public class KafkaConsumerConfig {</pre><pre>    @Bean<br>    public ConsumerFactory&lt;String, Order&gt; orderConsumerFactory(KafkaProperties props) {<br>        Map&lt;String, Object&gt; config = props.buildConsumerProperties();<br>        config.put(JsonDeserializer.VALUE_DEFAULT_TYPE, Order.class.getName());<br>        return new DefaultKafkaConsumerFactory&lt;&gt;(config);<br>    }</pre><pre>    @Bean<br>    public ConsumerFactory&lt;String, Payment&gt; paymentConsumerFactory(KafkaProperties props) {<br>        Map&lt;String, Object&gt; config = props.buildConsumerProperties();<br>        config.put(JsonDeserializer.VALUE_DEFAULT_TYPE, Payment.class.getName());<br>        return new DefaultKafkaConsumerFactory&lt;&gt;(config);<br>    }</pre><pre>    @Bean<br>    public ConcurrentKafkaListenerContainerFactory&lt;String, Order&gt; orderKafkaListenerFactory(<br>            ConsumerFactory&lt;String, Order&gt; orderConsumerFactory) {<br>        var factory = new ConcurrentKafkaListenerContainerFactory&lt;String, Order&gt;();<br>        factory.setConsumerFactory(orderConsumerFactory);<br>        return factory;<br>    }</pre><pre>    @Bean<br>    public ConcurrentKafkaListenerContainerFactory&lt;String, Payment&gt; paymentKafkaListenerFactory(<br>            ConsumerFactory&lt;String, Payment&gt; paymentConsumerFactory) {<br>        var factory = new ConcurrentKafkaListenerContainerFactory&lt;String, Payment&gt;();<br>        factory.setConsumerFactory(paymentConsumerFactory);<br>        return factory;<br>    }<br>}</pre><p>buildConsumerProperties() starts from everything in application.properties, so each factory keeps the shared settings and overrides only the default type. Recent Spring Boot versions provide this method with an SslBundles parameter, but the idea is the same. It is also the same pattern we used for multiple KafkaTemplate beans in the producer series: shared base configuration, one targeted override.</p><p>Each listener then names the container factory it should use:</p><pre>@KafkaListener(topics = &quot;order-events&quot;, containerFactory = &quot;orderKafkaListenerFactory&quot;)<br>public void consumeOrder(Order order) { ... }</pre><pre>@KafkaListener(topics = &quot;payment-events&quot;, containerFactory = &quot;paymentKafkaListenerFactory&quot;)<br>public void consumePayment(Payment payment) { ... }</pre><pre>Order ConsumerFactory    (default type Order)    → order-events listener   ✓<br>Payment ConsumerFactory  (default type Payment)  → payment-events listener ✓</pre><p><strong>Key concept</strong></p><p>Listeners built from the same ConsumerFactory share its configuration. When listeners need different deserialization settings, they need different factories, or at least per-listener property overrides.</p><p><strong>Section 12 takeaway</strong></p><p>Type headers plus mapping is the simplest working setup. When headers cannot be used, give each listener its own default type.</p><h3>13. Several Consumers, Same Topic: Concurrency</h3><p>The last question is about throughput. Our order-events topic has three partitions, but one consumer owns all three and processes them on one thread. If processing an order takes 50 ms, that consumer handles at most about 20 orders per second, no matter how many partitions exist.</p><p>To process partitions in parallel, we add consumers to the same group. Inside one application, one property is enough:</p><pre>spring.kafka.listener.concurrency=3</pre><p>Or for a single listener:</p><pre>@KafkaListener(topics = &quot;order-events&quot;, concurrency = &quot;3&quot;)</pre><h4>What concurrency creates</h4><p>With concurrency 3, the container factory builds a ConcurrentMessageListenerContainer that runs three child containers. Each child has its own KafkaConsumer and its own thread, and all three join order-consumer-group. The coordinator then spreads the partitions among them:</p><pre>order-consumer-group<br>    ├── consumer-1  →  P0<br>    ├── consumer-2  →  P1<br>    └── consumer-3  →  P2</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h-OP-SzgPYRGmU6-f_f9Yg.jpeg" /></figure><p>This respects the rule from Part 1: a KafkaConsumer is never shared between threads. Concurrency does not add threads to one consumer; it adds consumers.</p><h4>Ordering is still safe</h4><p>Each partition is still read by exactly one consumer, on one thread, in offset order. In the producer series, we used orderId as the key so that all events of one order land in the same partition. Those events are therefore still processed in order, even with concurrency 3. Only events of <em>different</em> orders are processed in parallel.</p><p>This is also why scaling with concurrency is safer than handing records to a thread pool inside the listener. A thread pool breaks the per-partition ordering, and as we saw in Part 1, it can let the container commit offsets for records that are still being processed.</p><h4>Partitions are the ceiling</h4><p>Within one group, a partition is never read by two consumers at the same time. So a consumer beyond the partition count has nothing to do:</p><pre>concurrency = 4, partitions = 3<br>    consumer-1 → P0<br>    consumer-2 → P1<br>    consumer-3 → P2<br>    consumer-4 → (no partition, idle)</pre><p>The idle consumer still holds a thread and a connection, and still takes part in every rebalance. It becomes useful only as a standby: if another consumer leaves, it can take over a partition.</p><p>The opposite case is fine. With six partitions and concurrency 3, each consumer owns two partitions.</p><h4>Counting consumers across instances</h4><p>Concurrency applies per application instance. If we run two instances of the service, each with concurrency 3:</p><pre>instances × concurrency = consumers in the group<br>    2      ×      3      =        6</pre><pre>partitions = 3  →  3 consumers active, 3 idle</pre><p>The partition count therefore sets the maximum parallelism of a consumer group, across all instances. Choosing it is a capacity decision made when the topic is created. And as the producer series showed, adding partitions later changes which partition each key maps to.</p><h4>Who gets which partition?</h4><p>The mapping between consumers and partitions is decided by the group’s assignment strategy:</p><pre>spring.kafka.consumer.properties.partition.assignment.strategy=...</pre><p>Range, round robin, sticky, and cooperative sticky distribute partitions differently, and they behave very differently when a consumer joins or leaves. Section 14 compares all four with the same example.</p><p><strong>Key concept</strong></p><p>Concurrency adds consumers to the same group, one thread each. Partitions are the unit of parallelism: more consumers than partitions adds no throughput, and per-key ordering is preserved because each partition still has a single reader.</p><h3>14. Partition Assignment Strategies</h3><p>In Part 1, we saw that one member of the group, the group leader, computes the partition assignment during a rebalance. How it divides the partitions is decided by the <strong>assignment strategy</strong>, configured on every consumer:</p><pre>spring.kafka.consumer.properties.partition.assignment.strategy=\<br>org.apache.kafka.clients.consumer.RangeAssignor<br># or org.apache.kafka.clients.consumer.RoundRobinAssignor<br># or org.apache.kafka.clients.consumer.StickyAssignor<br># or org.apache.kafka.clients.consumer.CooperativeStickyAssignor</pre><p>To compare them, we use the same example for all four:</p><pre>Topic:      order-events<br>Partitions: P0, P1, P2, P3, P4, P5<br>Consumers:  C1, C2, C3   (all in order-consumer-group)</pre><h4>Range Assignor (the default)</h4><p>The range assignor works per topic. It lays out the partitions in numeric order, the consumers in alphabetical order, and gives each consumer a contiguous range:</p><pre>6 partitions / 3 consumers = 2 each</pre><pre>C1: P0, P1<br>C2: P2, P3<br>C3: P4, P5</pre><p>When the division is not exact, the first consumers get one extra partition each. With 7 partitions, C1 would get P0, P1, P2.</p><p>Because it works topic by topic, those extras add up when a group reads several topics. Suppose C1 and C2 read two topics, each with 3 partitions:</p><pre>order-events   (3 partitions): C1 → P0, P1   C2 → P2<br>payment-events (3 partitions): C1 → P0, P1   C2 → P2</pre><pre>C1: 4 partitions,  C2: 2 partitions</pre><p>C1 always wins the remainder, on every topic, and ends up with twice the work.</p><p>The range assignor has one real advantage: the same partition numbers of different topics go to the same consumer. If order-events and payment-events are both keyed by orderId and have the same partition count, the order and payment events of one order are handled by the same consumer, which is useful for joining them.</p><h4>Round Robin Assignor</h4><p>The round robin assignor puts all partitions of all subscribed topics in one list, and deals them out one by one, like cards:</p><pre>C1: P0, P3<br>C2: P1, P4<br>C3: P2, P5</pre><p>Across several topics, the distribution stays as even as possible: no consumer ever has more than one partition more than another.</p><h4>Sticky Assignor</h4><p>The sticky assignor starts with an even distribution, just like round robin:</p><pre>C1: P0, P3<br>C2: P1, P4<br>C3: P2, P5</pre><p>Its real advantage only appears during a rebalance. It has two goals: keep the distribution as balanced as possible, and keep each consumer on the partitions it already owns. To see why that matters, we need to crash a consumer.</p><h4>When C3 crashes: range and round robin</h4><p>With the range and round robin assignors, the leader recomputes the whole assignment from scratch for the remaining consumers. With round robin, that gives:</p><pre>Before:  C1: P0, P3      C2: P1, P4      C3: P2, P5<br>After:   C1: P0, P2, P4  C2: P1, P3, P5</pre><p>Look at C1. It had P0 and P3. It now has P0, P2, and P4. It <strong>lost P3</strong>, even though P3’s consumer is perfectly healthy, and P3 now moves to C2. Only P2 and P5 actually needed a new owner, but four partitions changed hands.</p><p>Every move has a cost. The consumer losing a partition must commit its offsets and clean up whatever it held for it, such as an in-memory cache or a local state store. The consumer gaining a partition must fetch the committed offset and often warm up that state again.</p><h4>When C3 crashes: sticky</h4><p>The sticky assignor takes only the orphaned partitions, P2 and P5, and spreads them over the survivors:</p><pre>Before:  C1: P0, P3      C2: P1, P4      C3: P2, P5<br>After:   C1: P0, P3, P2  C2: P1, P4, P5</pre><p>C1 keeps P0 and P3. C2 keeps P1 and P4. Only the two partitions that had to move, moved. The result is as balanced as round robin, with the minimum number of changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uOtuiETgB2C_gZcgEqPTmA.jpeg" /></figure><h3>15. Rebalancing: Eager versus Cooperative</h3><p>The sticky assignor minimizes how many partitions move. But it does not change <em>how</em> the rebalance happens. Range, round robin, and sticky all use the <strong>eager</strong> rebalance protocol:</p><pre>Rebalance starts<br>    ↓<br>EVERY consumer revokes ALL of its partitions<br>    ↓<br>EVERY consumer stops reading<br>    ↓<br>Leader computes the new assignment<br>    ↓<br>Partitions handed out, everyone resumes</pre><p>Even with the sticky assignor, where C1 ends up with P0 and P3 again, C1 first gives them up and stops reading, and only gets them back when the whole rebalance is complete. For the duration of the rebalance, the entire group consumes nothing. This is the “stop-the-world” rebalance.</p><h4>Cooperative Sticky Assignor</h4><p>The CooperativeStickyAssignor combines the sticky assignment with the <strong>cooperative</strong> (incremental) protocol. Instead of revoking everything, it works in two steps:</p><ol><li>The leader computes the target assignment and determines which partitions must change owner. Every consumer keeps the partitions that stay with it, and keeps reading them.</li><li>Only the partitions that move are revoked from their old owner and assigned to their new owner, in a short follow-up rebalance.</li></ol><p>In our crash example, C1 never stops reading P0 and P3, and C2 never stops reading P1 and P4. The only partitions that pause are P2 and P5, which had no owner anyway.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ubpBqxjsg3TJHL7pGWNTFw.jpeg" /></figure><p>The difference grows with the size of the group. In a group of 20 consumers, adding one new instance during a rolling deployment would pause all 20 with an eager protocol. With the cooperative protocol, 19 keep working while a few partitions move to the newcomer.</p><p>For most Spring Boot services, this is the strategy to choose:</p><pre>spring.kafka.consumer.properties.partition.assignment.strategy=\<br>org.apache.kafka.clients.consumer.CooperativeStickyAssignor</pre><p>A note on defaults: in recent Kafka clients, the default value of partition.assignment.strategy is the list [RangeAssignor, CooperativeStickyAssignor]. The group uses the first strategy every member supports, which means range in practice. The second entry exists to make a later switch to cooperative possible. Switching an existing group from an eager strategy to the cooperative one should be done with a rolling restart in two steps: first deploy with both strategies listed, then deploy again with only the cooperative one, so that old and new members always share a common strategy.</p><h4>What happens to in-flight work during a rebalance</h4><p>A rebalance always raises the question from Part 1: what about records that were processed but not yet committed?</p><p>When partitions are revoked, the Spring listener container commits the offsets of the records it has already finished before giving the partitions up. Records that were fetched but not processed are simply fetched again by the new owner, starting from the committed offset.</p><p>That is safe when the rebalance is planned. When it is caused by a crash, there is nobody left to commit, and the new owner reprocesses everything since the last commit. Once again: listeners must be idempotent.</p><p>For partition-specific state, such as the cache mentioned above, Spring Kafka lets us react to these moves with a ConsumerAwareRebalanceListener, whose onPartitionsRevoked and onPartitionsAssigned methods are called as partitions leave and arrive.</p><h4>Avoiding rebalances on restart: static membership</h4><p>One more setting reduces rebalances during deployments. By default, a restarted consumer joins as a brand-new member, which triggers a rebalance when it leaves and another when it comes back.</p><p>With <strong>static membership</strong>, each instance gets a stable identity:</p><pre>spring.kafka.consumer.properties.group.instance.id=order-service-1</pre><p>When an instance with a known group.instance.id restarts within session.timeout.ms, the coordinator gives it back its previous partitions without any rebalance. Each instance must use a unique id, typically derived from the pod or host name.</p><p><strong>Key concept</strong></p><p>The assignment strategy decides <em>who</em> gets which partition; the rebalance protocol decides <em>whether everyone stops</em> while it changes. Range and round robin recompute from scratch, sticky moves as few partitions as possible, and cooperative sticky also lets every unaffected consumer keep reading during the rebalance.</p><h3>Part 2 takeaway</h3><p>Part 1 showed the consumer when everything works. Part 2 showed what it takes to keep it working:</p><ul><li><strong>Failures:</strong> wrap the deserializer with ErrorHandlingDeserializer to escape the poison-pill loop, retry with a back-off that fits the failure, and never let the last attempt silently drop a record. Send it to a dead-letter topic or another recoverer.</li><li><strong>One consumer, many topics:</strong> map records manually from Strings, or let JsonDeserializer map __TypeId__ headers through spring.json.type.mapping, ideally with logical tokens and @KafkaHandler.</li><li><strong>Several listeners:</strong> each gets its own consumer and thread, but they share one ConsumerFactory unless we give them their own configuration.</li><li><strong>Scaling:</strong> concurrency adds consumers, one thread each, up to the partition count.</li><li><strong>Assignment and rebalancing:</strong> prefer CooperativeStickyAssignor so that consumers keep their partitions and keep reading while the group changes, and consider static membership for frequent deployments.</li></ul><p>Put together with Part 1, we now have the full picture of a Kafka consumer in Spring Boot: how it joins its group, where it starts reading, how records are fetched, how progress is committed, how failures are contained, and how the work is shared and moved between consumers.</p><p>And the same guarantee runs through every section: Kafka consumers are at-least-once by design. Crashes, retries, and rebalances can all deliver a record twice. A consumer that treats every record as possibly already seen is a consumer that survives production.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b28a76fd46e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inside the Kafka Consumer: How Records Are Fetched, Processed, and Committed Part 1]]></title>
            <link>https://medium.com/@youssefelmessbahi/inside-the-kafka-consumer-how-records-are-fetched-processed-and-committed-part-1-daaf91a97c89?source=rss-573653523742------2</link>
            <guid isPermaLink="false">https://medium.com/p/daaf91a97c89</guid>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[kafka-consumer]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <dc:creator><![CDATA[YOUSSEF EL MESSBAHI]]></dc:creator>
            <pubDate>Fri, 20 Nov 2026 23:04:34 GMT</pubDate>
            <atom:updated>2026-11-20T23:04:34.246Z</atom:updated>
            <content:encoded><![CDATA[<h3>From @KafkaListener to the poll loop: what Spring Boot builds, how a consumer joins its group, where it starts reading, and when it is safe to move on.</h3><p>Consuming an event with Spring Kafka looks even simpler than producing one:</p><pre>@KafkaListener(topics = &quot;order-events&quot;)<br>public void consume(Order order) {<br>    System.out.println(&quot;Received order event: &quot; + order.getOrderId());<br>}</pre><p>This method creates a strong impression: Kafka receives an event, then pushes it into our application, which reacts.</p><p>That is not what happens. A Kafka broker never pushes records to a consumer. The consumer asks for them.</p><p>Kafka uses a <strong>pull</strong> model on purpose. Each consumer requests data when it is ready, at its own pace. A slow consumer does not get flooded, a fast one can request large batches, and any consumer can go back and re-read older records because they are still stored in the log.</p><p>Before the first record reaches the method above, the consumer has already gone through a long sequence of steps:</p><pre>Spring Boot application starts<br>    ↓<br>1. ConsumerFactory + Listener Container<br>    ↓<br>2. KafkaConsumer finds its group coordinator<br>    ↓<br>3. KafkaConsumer joins the consumer group<br>    ↓<br>4. Partitions are assigned<br>    ↓<br>5. Committed offsets are fetched<br>    ↓<br>6. FetchRequest to partition leaders<br>    ↓<br>7. Deserializer → @KafkaListener method<br>    ↓<br>8. Offset commit</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ste-BcN3zbqvxXbaGuusgw.png" /></figure><p>Spring Boot creates the infrastructure that owns a KafkaConsumer. The consumer locates the broker that manages its group, joins that group, and receives a set of partitions. For each partition, it asks where the group stopped last time. It then fetches records from the partition leaders, deserializes them, hands them to our method, and finally records its progress by committing offsets.</p><p>The steps before the listener decide <em>which</em> records this consumer reads. The step after it decides what happens to those records if the application crashes.</p><p>In this article, we will set up a basic consumer, then follow a record through each stage. Along the way, we will see why one slow listener can trigger a rebalance, why a brand-new consumer group can silently skip every existing event, and why the moment of the offset commit decides whether a crash loses events or processes them twice.</p><p>If you have read the producer series (<a href="https://medium.com/@youssefelmessbahi/inside-the-kafka-producer-how-records-are-batched-sent-and-protected-from-duplicates-part-1-a8a0b9e12e2f">Part 1</a>, <a href="https://medium.com/@youssefelmessbahi/inside-the-kafka-producer-how-records-are-batched-sent-and-protected-from-duplicates-part-2-956d98a05fbd">Part 2</a>), this is the other side of the same order-events topic.</p><h3>1. Setting Up a Basic Consumer with Spring Boot</h3><p>We will consume the Order events that the producer series published to order-events.</p><h4>Step 1: Add Spring Kafka</h4><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.kafka&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-kafka&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><h4>Step 2: Configure the consumer</h4><pre>server.port=8082<br>spring.application.name=kafka-consumer-service</pre><pre>spring.kafka.bootstrap-servers=localhost:9092,localhost:9192</pre><pre># Which consumer group this consumer joins<br>spring.kafka.consumer.group-id=order-consumer-group</pre><pre># Must mirror the serializers used by the producer<br>spring.kafka.consumer.key-deserializer=\<br>org.apache.kafka.common.serialization.StringDeserializer<br>spring.kafka.consumer.value-deserializer=\<br>org.springframework.kafka.support.serializer.JsonDeserializer</pre><pre># JSON carries no Java type: tell the deserializer which class to build<br>spring.kafka.consumer.properties.spring.json.value.default.type=\<br>com.eda.consumer.model.Order</pre><h4>Step 3: Create the event class</h4><pre>public class Order {<br>    private String orderId;<br>    private String customerId;<br>    private String productId;<br>    private Integer quantity;<br>    private Double totalAmount;<br>    private String status;<br>    // getters and setters<br>}</pre><h4>Step 4: Listen to the topic</h4><pre>@Component<br>public class OrderEventListener {</pre><pre>    @KafkaListener(topics = &quot;order-events&quot;)<br>    public void consume(Order order) {<br>        // Executed once for every record<br>        System.out.println(&quot;Received order event: &quot; + order.getOrderId());<br>    }<br>}</pre><p>Start the application, publish an order from the producer, and the listener prints it.</p><p>Four small steps. But three of the configuration lines deserve a closer look, because each one hides a design decision.</p><h4>bootstrap-servers is an entry point, not the cluster</h4><pre>spring.kafka.bootstrap-servers=localhost:9092,localhost:9192</pre><p>The consumer does not need to know every broker. It connects to any one of these addresses, downloads the cluster metadata, and from then on knows every broker, every topic, and which broker leads each partition.</p><p>Listing more than one address is only about availability at startup. If the first broker is down, the consumer tries the next one.</p><h4>group-id: one setting, two messaging models</h4><pre>spring.kafka.consumer.group-id=order-consumer-group</pre><p>A <strong>consumer group</strong> is a set of consumers that share the work of reading a topic. Inside one group, each partition is read by exactly one consumer at a time.</p><p>Different groups are completely independent. Each group keeps its own position in the topic and receives every record.</p><pre>order-events<br>    │<br>    ├──→ order-consumer-group      (processes orders)<br>    │       consumer-1 → P0, P1<br>    │       consumer-2 → P2<br>    │<br>    └──→ analytics-group           (builds reports)<br>            consumer-1 → P0, P1, P2</pre><p>Inside a group, Kafka behaves like a queue: the work is divided. Across groups, it behaves like publish-subscribe: everyone gets a copy. The same topic serves both models, and the group id decides which one we get.</p><p>This is also why the group id is not optional when we subscribe to a topic. A plain KafkaConsumer that calls subscribe() without a group.id fails with an InvalidGroupIdException. Without a group, there is nobody to share partitions with and nowhere to store progress.</p><h4>The deserializers are the other half of the contract</h4><p>In the producer series, we saw that Kafka stores only bytes. The producer chose StringSerializer for the key and JsonSerializer for the value. The consumer must reverse exactly that:</p><pre>Producer:  &quot;ORD-1001&quot; → StringSerializer → bytes<br>           Order      → JsonSerializer   → JSON bytes</pre><pre>Consumer:  bytes      → StringDeserializer → &quot;ORD-1001&quot;<br>           JSON bytes → JsonDeserializer   → Order</pre><p>There is one asymmetry. When the producer serialized the order, it knew the Java type: the object was an Order. When the consumer receives JSON bytes, that information is gone:</p><pre>{ &quot;orderId&quot;: &quot;ORD-1001&quot;, &quot;quantity&quot;: 2, &quot;status&quot;: &quot;CREATED&quot; }</pre><p>Nothing in this text says which class it should become. That is the job of value.default.type: it tells JsonDeserializer to build a com.eda.consumer.model.Order.</p><p>Note that the consumer’s Order class does not have to be the producer&#39;s class. It lives in the consumer&#39;s own package and only needs matching field names. Part 2 shows how a consumer chooses between several classes when one listener receives different event types.</p><h4>What happens when deserialization fails?</h4><p>Suppose another service publishes a record whose value is not valid JSON.</p><p>The failure happens inside the consumer client, while it turns fetched bytes into objects. Our listener never sees the record:</p><pre>Fetched bytes<br>    ↓<br>JsonDeserializer<br>    ↓<br>Deserialization error<br>    ✕<br>No Order object<br>No listener call</pre><p>A record like this is often called a <strong>poison pill</strong>: it cannot be processed, and if the consumer simply retries, it fails the same way each time.</p><p>Spring Kafka provides ErrorHandlingDeserializer for this case. It wraps the real deserializer and catches the failure, so the bad record is passed to the container&#39;s error handler instead of breaking consumption:</p><pre>spring.kafka.consumer.value-deserializer=\<br>org.springframework.kafka.support.serializer.ErrorHandlingDeserializer<br>spring.kafka.consumer.properties.spring.deserializer.value.delegate.class=\<br>org.springframework.kafka.support.serializer.JsonDeserializer</pre><p>The error handler can then log the record, skip it, or send it to a dead-letter topic, and the consumer moves on to the next record.</p><p><strong>Key concept</strong></p><p>The group id decides who shares the work and where progress is stored. The deserializers decide whether the bytes written by the producer can become objects again. Both are part of the contract between producer and consumer.</p><p><strong>Section 1 takeaway</strong></p><p>Four steps give us a working consumer: a dependency, a group id, matching deserializers, and a @KafkaListener.</p><p>But nothing in that code creates a KafkaConsumer, calls poll(), or commits an offset. So who does?</p><h3>2. What Spring Boot Builds Behind the Annotation</h3><p>When the application starts, Spring Boot assembles the consumer infrastructure in two branches.</p><pre>Spring Boot application starts<br>    │<br>    ├── KafkaAutoConfiguration   (spring-kafka on the classpath)<br>    │       ├── ConsumerFactory<br>    │       │     reads spring.kafka.consumer.* into a Map<br>    │       └── ConcurrentKafkaListenerContainerFactory<br>    │             holds the ConsumerFactory<br>    │             (no KafkaConsumer exists yet)<br>    │<br>    └── @EnableKafka   (added automatically by Spring Boot)<br>            └── KafkaListenerAnnotationBeanPostProcessor<br>                    ├── scans every @KafkaListener<br>                    └── for each one, asks the container factory<br>                        for a KafkaListenerContainer<br>                              ↓<br>                        container gets a KafkaConsumer<br>                        from the ConsumerFactory<br>                              ↓<br>                        poll loop starts</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5A4j9VhGzHOQ0iUWIBPz-w.png" /></figure><p>Each object in this chain has a single responsibility.</p><h4>ConsumerFactory: a recipe, not a consumer</h4><p>The ConsumerFactory reads every spring.kafka.consumer.* property into a configuration map. It does not connect to Kafka and it does not create a consumer at startup. It only knows <em>how</em> to create one when asked.</p><h4>ConcurrentKafkaListenerContainerFactory: a factory of containers</h4><p>This factory holds a reference to the ConsumerFactory, plus listener settings such as concurrency and acknowledgement mode. Its job is to build a listener container for each @KafkaListener method.</p><h4>The listener container: where the work happens</h4><p>When KafkaListenerAnnotationBeanPostProcessor finds our annotated method, it asks the container factory for a container. The container then:</p><ol><li>asks the ConsumerFactory for a new KafkaConsumer,</li><li>subscribes it to the topics named in the annotation,</li><li>starts a dedicated thread that runs the poll loop,</li><li>calls our method for each record,</li><li>commits offsets according to its acknowledgement mode.</li></ol><h4>Why one thread per consumer?</h4><p>KafkaConsumer is <strong>not thread-safe</strong>. If two threads call it at the same time, it throws a ConcurrentModificationException. So every container owns exactly one consumer and drives it from exactly one thread.</p><p>This has a direct consequence that surprises many developers: <strong>our listener runs on the same thread as the poll loop</strong>.</p><pre>Consumer thread<br>    ↓<br>poll() → returns up to 500 records<br>    ↓<br>listener(record 1)<br>listener(record 2)<br>...<br>listener(record 500)<br>    ↓<br>poll() again</pre><p>While our method processes a record, the consumer is not polling. If processing is slow, the next poll() is delayed. Section 3 shows why that delay has a hard limit.</p><p><strong>Key concept</strong></p><p>@KafkaListener does not consume anything by itself. It tells Spring to build a listener container, and the container owns the KafkaConsumer, its thread, and its poll loop.</p><p><strong>Section 2 takeaway</strong></p><pre>ConsumerFactory → ListenerContainer → KafkaConsumer → poll loop → @KafkaListener</pre><p>Every listener built from the same ConsumerFactory inherits the same configuration. That detail looks harmless now, but it is the root of a common bug we will meet in Part 2.</p><p>To understand what the container does on every iteration, we need to write the poll loop without Spring.</p><h3>3. The Poll Loop: What the Consumer Does Without Spring</h3><p>Conceptually, this is what the listener container does for us:</p><pre>Properties props = new Properties();<br>props.put(&quot;bootstrap.servers&quot;, &quot;localhost:9092,localhost:9192&quot;);<br>props.put(&quot;group.id&quot;, &quot;order-consumer-group&quot;);<br>props.put(&quot;key.deserializer&quot;, StringDeserializer.class);<br>props.put(&quot;value.deserializer&quot;, JsonDeserializer.class);<br>props.put(&quot;auto.offset.reset&quot;, &quot;latest&quot;);<br>props.put(&quot;enable.auto.commit&quot;, &quot;true&quot;);</pre><pre>KafkaConsumer&lt;String, Order&gt; consumer = new KafkaConsumer&lt;&gt;(props);</pre><pre>// Which topics this consumer is interested in<br>consumer.subscribe(List.of(&quot;order-events&quot;));</pre><pre>try {<br>    while (true) {<br>        ConsumerRecords&lt;String, Order&gt; records =<br>            consumer.poll(Duration.ofMillis(500));</pre><pre>        for (ConsumerRecord&lt;String, Order&gt; record : records) {<br>            // business logic<br>        }<br>    }<br>} finally {<br>    consumer.close(); // leaves the consumer group<br>}</pre><p>Two lines in this code look simple and are not.</p><h4>subscribe() sends nothing</h4><p>Calling subscribe() only records which topics the consumer wants. No request is sent, no group is joined, no partition is assigned. All of that happens later, inside poll().</p><h4>poll() changes its behavior over time</h4><p>The same method call does very different work depending on the consumer’s state:</p><pre>First poll()<br>    ↓<br>Find the group coordinator<br>    ↓<br>Join the group<br>    ↓<br>Receive partition assignment<br>    ↓<br>Fetch the last committed offset per partition<br>    ↓<br>FetchRequest to each partition leader</pre><pre>Later poll() calls<br>    ↓<br>FetchRequest for the next offsets<br>    ↓<br>Auto-commit, if enabled and the interval has passed</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6BjL2jCtdL_iSqQNshOWzA.png" /></figure><p>The first call turns a configured object into a member of a group. Every later call is about moving through the partitions it owns.</p><h4>What poll() actually returns</h4><p>poll() does not return one record. It returns a batch, up to max.poll.records (500 by default), taken from all the partitions this consumer owns. Section 6 opens up exactly how that batch is fetched and sized.</p><p>The duration we pass is the longest the call may block waiting for data. If records are already available, it returns immediately. If nothing arrives in time, it returns an empty batch and the loop simply continues. In Spring Kafka, the container passes this value for us:</p><pre># How long one poll() may wait for records (5 seconds, the default)<br>spring.kafka.listener.poll-timeout=5000</pre><h4>Two different ways to be considered dead</h4><p>A consumer group must detect members that disappear. Kafka checks two separate things:</p><pre># Is the process alive?<br># A background thread sends a heartbeat to the coordinator every 3 seconds<br>spring.kafka.consumer.properties.heartbeat.interval.ms=3000<br># No heartbeat for 45 seconds → consumer considered dead → rebalance<br>spring.kafka.consumer.properties.session.timeout.ms=45000</pre><pre># Is the consumer making progress?<br># The coordinator expects at least one poll() every 5 minutes<br>spring.kafka.consumer.properties.max.poll.interval.ms=300000</pre><p>Heartbeats are sent by a background thread, independently of our code. They prove the process is running. The session timeout is deliberately several heartbeats long, so that one lost heartbeat on a busy network does not trigger a rebalance.</p><p>The second check is about our code. If the time between two poll() calls exceeds max.poll.interval.ms, the consumer is considered stuck, it leaves the group, and its partitions are given to someone else.</p><p>Now connect this to Section 2. Our listener runs on the poll thread. If one batch of 500 records takes more than five minutes to process, for example because each record calls a slow external API, the consumer is removed from the group while it is still working. When it finally commits, the commit is rejected because it no longer owns those partitions, and another consumer processes the same records again.</p><p>The usual fixes are to make processing faster, lower max.poll.records so each batch is smaller, or raise max.poll.interval.ms when long processing is expected.</p><p><strong>Key concept</strong></p><p>Kafka consumers pull. Every record a consumer processes is the result of a poll() call, the first poll() is where the consumer joins its group, and calling poll() regularly is how the consumer proves it is still making progress.</p><p><strong>Section 3 takeaway</strong></p><p>The poll loop has three responsibilities: join the group once, fetch records continuously, and record progress through offset commits.</p><p>The first of those starts with a question: which broker manages this consumer group?</p><h3>4. Joining the Group: Finding the Group Coordinator</h3><p>Every consumer group is managed by one broker, called the <strong>group coordinator</strong>. The coordinator:</p><ul><li>tracks which consumers are members of the group,</li><li>receives their heartbeats,</li><li>triggers a rebalance when membership changes,</li><li>stores the offsets the group commits.</li></ul><p>A consumer belongs to exactly one group: the group.id is a single value in its configuration. To read the same topic for two different purposes, we create two consumers with two group ids, not one consumer in two groups.</p><p>A cluster may host thousands of groups. If one broker coordinated all of them, it would become a bottleneck. So Kafka spreads the coordinator role across brokers, and it does so deterministically, without any central registry.</p><h4>How the coordinator is chosen</h4><p>The choice is derived from the group id and the internal __consumer_offsets topic, which has 50 partitions by default (offsets.topic.num.partitions):</p><pre>Step 1: Consumer starts with group.id = &quot;order-consumer-group&quot;<br>    ↓<br>Step 2: Find its partition of __consumer_offsets<br>        abs(hash(&quot;order-consumer-group&quot;)) % 50  →  e.g. 23<br>    ↓<br>Step 3: Send a FindCoordinator request to any broker<br>        (who leads __consumer_offsets partition 23?)<br>    ↓<br>Step 4: Contact that leader → it is the group coordinator<br>        → send JoinGroupRequest</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LAldlOhhOR8FmcOaWLawcA.png" /></figure><p>The leader of that __consumer_offsets partition becomes the coordinator for the group.</p><p>This idea should feel familiar. In the producer series, a record key was hashed to choose a partition, so the same key always reached the same place. Here, the group id is hashed to choose a partition of __consumer_offsets, so every member of the same group reaches the same coordinator. Different groups hash to different partitions, which spreads coordinator work across the brokers.</p><h4>Joining: two round trips</h4><p>The JoinGroupRequest carries two important pieces of information: the group the consumer wants to join, and the topics it subscribes to. The coordinator needs both, because the assignment can only divide partitions of topics that members actually asked for.</p><p>With the classic group protocol, joining takes two requests:</p><pre>JoinGroupRequest   →  coordinator collects all members<br>                       and elects one consumer as group leader<br>SyncGroupRequest   →  the group leader computes the assignment;<br>                       the coordinator sends each member its partitions</pre><p>One detail is easy to miss: the assignment is computed by one of the <strong>consumers</strong>, not by the broker. The coordinator only collects members and distributes the result. Keeping the assignment logic in the client lets applications plug in their own strategy without upgrading brokers.</p><p>The strategy itself can be range, round robin, sticky, or cooperative sticky. They differ in how evenly they spread partitions and in how much they move during a rebalance. Part 2 compares all four with the same example.</p><p>Newer Kafka versions also offer a consumer group protocol (KIP-848) in which the broker computes assignments and rebalances happen incrementally. The roles of coordinator, membership, and assignment stay the same.</p><h4>What a rebalance is, and what triggers it</h4><p>A <strong>rebalance</strong> is the process of redistributing partitions among the members of a group. It happens when:</p><ul><li>a consumer joins the group,</li><li>a consumer leaves it, through close() or a crash,</li><li>a consumer exceeds max.poll.interval.ms,</li><li>partitions are added to a subscribed topic,</li><li>the coordinator broker itself changes.</li></ul><p>With the classic eager approach, every member gives up all its partitions during the rebalance, and consumption pauses for the whole group until the new assignment is in place. That pause is the reason frequent rebalances hurt throughput, and the reason the cooperative strategies were introduced.</p><h4>Where group information lives</h4><p>The coordinator keeps the live membership of the group in memory. Committed offsets are written to __consumer_offsets, which is replicated like any other topic.</p><p>So if the coordinator broker fails, the group is not lost. A follower becomes leader of partition 23 of __consumer_offsets and with it the new coordinator. The consumers discover the new coordinator, rejoin, and a rebalance happens. The committed offsets are still there.</p><h4>How often metadata is refreshed</h4><p>The consumer downloads cluster metadata from one of the bootstrap brokers and caches it: the list of brokers, the partitions of each topic, and the leader of each partition. Every later request is routed with this cache.</p><p>The cache is refreshed in two ways.</p><p><strong>Periodically</strong>, by default every 5 minutes:</p><pre>spring.kafka.consumer.properties.metadata.max.age.ms=300000</pre><p><strong>On demand</strong>, whenever the cache turns out to be wrong or incomplete. For example, a broker answers NOT_LEADER_OR_FOLLOWER because the partition&#39;s leadership moved to another broker after a failure, or the consumer needs information about a topic that is not in its cache yet.</p><p>The periodic refresh is how a consumer eventually notices changes nobody told it about, such as new partitions added to a topic it subscribes to.</p><p><strong>Key concept</strong></p><p>The group coordinator is the leader of the __consumer_offsets partition selected by hash(group.id) % 50. It manages membership and stores offsets, while one consumer in the group computes the partition assignment.</p><p><strong>Section 4 takeaway</strong></p><p>After joining, the consumer knows which partitions it owns. But owning partition 0 is not enough. The consumer must also know where to start reading in it.</p><h3>5. Where to Start Reading: Committed Offsets</h3><p>Every record in a partition has an <strong>offset</strong>: its position in the log. The group’s <strong>committed offset</strong> for a partition is its bookmark in that log.</p><p>One detail matters a lot: the committed offset is the offset of the <strong>next record to read</strong>, not the last record processed.</p><pre>order-events-0</pre><pre>Offset:  38   39   40   41   42   43   44<br>         ✓    ✓    ✓    ✓    ·    ·    ·<br>                             ↑<br>                committed offset = 42<br>                (records up to 41 are done)</pre><p>For each assigned partition, the consumer asks the coordinator for this value with an OffsetFetch request. The coordinator reads it from __consumer_offsets:</p><pre>Assigned partition: order-events-0<br>    ↓<br>OffsetFetch → group coordinator<br>    ↓<br>Committed offset = 42<br>    ↓<br>FetchRequest(order-events-0, offset 42) → partition leader</pre><p>Notice where each request goes. Offsets come from the coordinator, but the records themselves are fetched from the leader of each partition. A consumer that owns partitions led by three different brokers fetches from all three in parallel.</p><h4>Why the bookmark belongs to the group</h4><p>The committed offset is stored per group and per partition, not per consumer. That is what makes rebalancing safe.</p><p>When partition 0 moves from consumer-1 to consumer-2, consumer-2 asks the coordinator for the group’s committed offset and continues from offset 42. It does not need to know anything about consumer-1.</p><h4>What if there is no committed offset?</h4><p>A brand-new group has never committed anything. In that case, auto.offset.reset decides where to start:</p><ul><li>latest (default): start after the last existing record. Only new records are read.</li><li>earliest: start from the oldest record still retained in the partition.</li><li>none: throw an exception and let the application decide.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IRJvDzij8AYT1zZbjvMTwg.png" /></figure><p>The default is a common surprise. Suppose the producer has already published 10,000 orders, and we deploy a new service with a new group id to process them. With latest, that service starts after the 10,000th order and silently ignores all of them. No error, no warning.</p><p>A new service that must process history should start with:</p><pre>spring.kafka.consumer.auto-offset-reset=earliest</pre><h4>Two more situations where the reset applies</h4><p>auto.offset.reset is not only for brand-new groups. It also applies when a committed offset exists but can no longer be used:</p><ul><li><strong>The offsets expired.</strong> When a group has no active members, its committed offsets are deleted after offsets.retention.minutes (7 days by default). A service that is stopped for longer than that comes back with no bookmark.</li><li><strong>The data expired.</strong> If the committed offset points to records already removed by the topic’s retention policy, that position no longer exists, and the consumer falls back to the reset policy.</li></ul><p>In both cases, a consumer configured with latest skips everything in between, again without an error.</p><h4>Seeing where a group stands</h4><p>Kafka ships a tool that shows each partition’s committed offset next to the end of the log:</p><pre>kafka-consumer-groups.sh --bootstrap-server localhost:9092 \<br>  --describe --group order-consumer-group</pre><pre>TOPIC         PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG<br>order-events  0          42              45              3<br>order-events  1          108             108             0<br>order-events  2          77              80              3</pre><p>CURRENT-OFFSET is the committed offset. LOG-END-OFFSET is where the next produced record will land. The difference is the <strong>consumer lag</strong>: how many records the group still has to process. A lag that keeps growing means the consumers cannot keep up with the producers.</p><p><strong>Key concept</strong></p><p>The committed offset is the group’s bookmark: the next record to read in each partition. When it is missing or unusable, auto.offset.reset decides, and its default of latest skips existing records.</p><p><strong>Section 5 takeaway</strong></p><p>The consumer now knows, for every partition it owns, which offset to read next. The next question is how those records actually travel from the brokers into the batch returned by poll().</p><h3>6. Inside poll(): How Records Are Fetched</h3><p>Our consumer owns three partitions of order-events. Suppose their leaders are spread over two brokers:</p><pre>order-events-0  → leader Broker 1   (next offset 10)<br>order-events-1  → leader Broker 2   (next offset 5)<br>order-events-2  → leader Broker 1   (next offset 20)</pre><p>The consumer does not send one request per partition. It groups its partitions by leader and sends <strong>one FetchRequest per broker</strong>, listing every partition that broker leads and the offset to start from:</p><pre>FetchRequest → Broker 1<br>    Topic: order-events<br>        Partition 0, from offset 10<br>        Partition 2, from offset 20</pre><pre>FetchRequest → Broker 2<br>    Topic: order-events<br>        Partition 1, from offset 5</pre><p>This is the same idea we saw in the producer’s sender thread, which grouped batches by leader broker. A single request can even cover several topics, if the consumer subscribes to more than one.</p><p>Each broker answers with a FetchResponse containing records for each requested partition. The consumer merges the responses into one ConsumerRecords object, organized by topic and partition:</p><pre>ConsumerRecords<br>    order-events-0:  offset 10 → A,  offset 11 → B<br>    order-events-1:  offset 5  → C<br>    order-events-2:  offset 20 → D,  offset 21 → E</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ntIFAkMqO9z1Jq0BE4iI1Q.png" /></figure><h4>How much data does one fetch return?</h4><p>Fetching is limited by <strong>bytes</strong>, not by number of records. Two settings define the ceiling:</p><pre># Max data a broker returns PER partition (1 MB)<br>spring.kafka.consumer.properties.max.partition.fetch.bytes=1048576</pre><pre># Max data a broker returns in ONE response, all partitions combined (50 MB)<br>spring.kafka.consumer.properties.fetch.max.bytes=52428800</pre><p>So a response from Broker 1 can carry up to 1 MB from partition 0 and up to 1 MB from partition 2, and never more than 50 MB in total.</p><p>Two more settings decide <strong>when</strong> the broker answers:</p><pre># Minimum data the broker must have before responding<br>spring.kafka.consumer.properties.fetch.min.bytes=1</pre><pre># How long the broker may hold the request to reach fetch.min.bytes<br>spring.kafka.consumer.properties.fetch.max.wait.ms=500</pre><p>The broker responds as soon as one of two conditions is met:</p><ol><li>the data accumulated reaches fetch.min.bytes, or</li><li>fetch.max.wait.ms has passed, in which case it sends whatever it has, possibly nothing.</li></ol><p>With the defaults, the broker answers as soon as a single byte is available. This is the consumer’s mirror image of linger.ms and batch.size from the producer series. Raising fetch.min.bytes to, say, 64 KB makes the broker wait to fill a bigger response: fewer requests, more records per round trip, slightly higher latency. A throughput-oriented consumer accepts that trade; a latency-sensitive one keeps the default.</p><h4>max.poll.records and the internal buffer</h4><p>Because fetch limits are expressed in bytes, a single response can contain far more records than we expect. A 50 MB response of small JSON events could carry tens of thousands of records.</p><p>That is what max.poll.records is for:</p><pre># Max records returned by ONE poll() call<br>spring.kafka.consumer.properties.max.poll.records=500</pre><p>It does not limit what the broker sends. It limits what poll() hands to our code:</p><pre>FetchResponse: 2,000 records<br>    ↓<br>Consumer internal buffer: 2,000 records<br>    ↓<br>poll() #1 → returns 500   (1,500 stay in the buffer)<br>poll() #2 → returns 500   (no network call, served from the buffer)<br>poll() #3 → returns 500<br>poll() #4 → returns 500<br>poll() #5 → buffer empty → new FetchRequest</pre><p>Every poll() checks the buffer first, and only goes to the network when the buffer runs low. In practice, the client also prefetches the next batch in the background while we process the current one, so the brokers are rarely waiting on us.</p><p>This is also the most direct lever on the max.poll.interval.ms problem from Section 3. If each record takes 1 second to process, a batch of 500 needs over 8 minutes, longer than the 5-minute limit. Lowering max.poll.records to 100 makes each batch fit comfortably.</p><h4>Pausing between polls</h4><p>By default, the Spring container calls poll() again as soon as the previous batch is processed. A delay can be added between polls:</p><pre># Sleep between two poll() calls (0 = poll again immediately, the default)<br>spring.kafka.listener.idle-between-polls=0</pre><p>This is rarely needed. It can help to slow down a consumer that would otherwise overload a downstream system, as long as the total time between polls stays below max.poll.interval.ms.</p><p><strong>Key concept</strong></p><p>The consumer sends one FetchRequest per leader broker, the broker sizes its answer in bytes, and max.poll.records only controls how many buffered records each poll() hands to our code.</p><p><strong>Section 6 takeaway</strong></p><p>The records are now in our listener. The remaining question decides correctness: when is it safe to move the bookmark?</p><h3>7. Committing Offsets: Auto, Sync, and Async</h3><p>Committing an offset tells the group: everything before this position is done. If the consumer crashes, whoever takes over the partition starts from the last commit.</p><p>So the real question is not <em>how</em> to commit, but <em>when</em>. Commit too early and a crash loses records. Commit too late and a crash processes records twice.</p><h4>Auto commit</h4><pre>enable.auto.commit=true<br>auto.commit.interval.ms=5000   # default</pre><p>With auto commit, the consumer commits on a timer. The commit is not sent from a separate thread: it happens inside poll(), at most every 5 seconds. Conceptually:</p><pre>poll() {<br>    if (autoCommitEnabled &amp;&amp; commitIntervalPassed) {<br>        commitOffsets(); // positions of records already returned<br>    }<br>    fetch new records<br>}</pre><p>The timer has no idea whether our business logic succeeded. That leads to two failure scenarios.</p><p><strong>Duplicates.</strong> The consumer processes records 42 to 99, and crashes before the next timer-driven commit. The last committed offset is still 42. The consumer that takes over starts at 42 and processes those records again.</p><p><strong>Loss.</strong> In the simple loop above, the records returned by one poll() are processed before the next poll(), so a commit only covers finished work. But if the listener hands records to another thread pool and returns immediately, the next poll() can commit offsets for records that are still in progress. If the application crashes then, those records are never processed by anyone.</p><pre>Crash after commit, before processing finished  →  events lost<br>Crash after processing, before the next commit  →  events reprocessed</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yUPhs_FJirwUxV7NtyBreg.png" /></figure><h4>Manual commit</h4><p>With enable.auto.commit=false, the application decides when to commit, usually right after processing:</p><pre>while (true) {<br>    ConsumerRecords&lt;String, Order&gt; records = consumer.poll(Duration.ofMillis(500));<br>    for (ConsumerRecord&lt;String, Order&gt; record : records) {<br>        process(record.value());<br>    }<br>    consumer.commitSync(); // blocks until the broker confirms<br>}</pre><p>There are two ways to send the commit:</p><pre>consumer.commitSync();  // blocks, retries on recoverable errors<br>consumer.commitAsync(); // returns immediately, no retry</pre><p>commitSync() is safe but adds a round trip to every loop iteration. commitAsync() keeps the loop fast, but it deliberately does not retry. Imagine an async commit of offset 100 fails and is retried later, after a newer commit of offset 200 has already succeeded. The retry would move the bookmark back to 100, and the group would reprocess 100 records after the next restart.</p><p>A common pattern combines both: commitAsync() inside the loop for speed, and one final commitSync() before close() so the last position is recorded reliably.</p><h4>What Spring Kafka does by default</h4><p>Spring Kafka sets enable.auto.commit=false by default and lets the listener container commit instead. The behavior is controlled by the container&#39;s <strong>AckMode</strong>:</p><pre># Let the container commit, not the Kafka client&#39;s timer (the default)<br>spring.kafka.consumer.enable-auto-commit=false<br>spring.kafka.listener.ack-mode=batch</pre><p>There are six modes. Each one answers the same question differently: after how much processed work do we send a commit?</p><p><strong>BATCH (default).</strong> poll() returns up to 500 records, the listener processes all of them, and the container sends one commit for the whole batch. One commit request per poll keeps overhead low. The cost appears on a crash: if the application dies while processing record 480, nothing from this batch has been committed yet, and all 480 processed records are delivered again after the restart.</p><p><strong>RECORD.</strong> The container commits after every single record. A crash repeats at most the record in progress. The cost is overhead: 500 records mean 500 commit requests to the coordinator, which can noticeably reduce throughput.</p><p><strong>TIME and COUNT.</strong> Middle grounds between the two. The container commits when a time interval has passed, or after a number of records:</p><pre>spring.kafka.listener.ack-mode=time<br>spring.kafka.listener.ack-time=5000    # commit every 5 seconds</pre><pre>spring.kafka.listener.ack-mode=count<br>spring.kafka.listener.ack-count=10     # commit every 10 records</pre><p>Unlike the client’s auto commit, these commits still only cover records the listener has finished.</p><p><strong>MANUAL and MANUAL_IMMEDIATE.</strong> The listener decides when a record counts as done. It receives an Acknowledgment parameter and calls it explicitly:</p><pre>spring.kafka.listener.ack-mode=manual</pre><pre>@KafkaListener(topics = &quot;order-events&quot;)<br>public void consume(ConsumerRecord&lt;String, Order&gt; record, Acknowledgment ack) {<br>    orderService.process(record.value());<br>    ack.acknowledge(); // only now does this record count as done<br>}</pre><p>The two manual modes look identical in code, but they differ in when the commit is sent:</p><ul><li>MANUAL: acknowledge() only marks the record. The container collects the acknowledgements and sends one commit after the whole batch from poll() has been handled, like BATCH.</li><li>MANUAL_IMMEDIATE: every acknowledge() sends a commit request right away, like RECORD.</li></ul><p>Manual acknowledgement is useful when “done” is not the same as “the method returned”, for example when a record is only complete after an asynchronous database write confirms. In Part 2, we will also see how errors interact with these commits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J9r2SYbA3qCtUHuEIJOkkQ.png" /></figure><h4>At-least-once, and why duplicates are normal</h4><p>Committing after processing gives <strong>at-least-once</strong> delivery: every record is processed, but some may be processed twice after a crash or a rebalance. Committing before processing gives <strong>at-most-once</strong>: no duplicates, but records can be lost.</p><p>Most systems choose at-least-once and make processing <strong>idempotent</strong>, so that handling the same record twice has the same effect as handling it once. For our orders, that can be as simple as ignoring an orderId that has already been stored.</p><p>This mirrors what we saw on the producer side: the idempotent producer prevents duplicates <em>in the log</em>, but it cannot prevent a consumer from <em>processing</em> a record twice. True end-to-end exactly-once processing requires Kafka transactions and consumers reading with isolation.level=read_committed, which is a topic of its own.</p><h4>Leaving the group</h4><p>There are two ways a consumer leaves its group, and they behave very differently:</p><pre>consumer.close()           →  LeaveGroup sent  →  rebalance right away<br>process crashes or hangs   →  heartbeats stop  →  rebalance after session.timeout.ms</pre><p>A clean shutdown tells the coordinator immediately, so its partitions are reassigned within moments. A crash says nothing. The coordinator only notices when heartbeats have been missing for session.timeout.ms (45 seconds by default), and those partitions are not consumed by anyone in the meantime.</p><p><strong>Key concept</strong></p><p>The moment of the commit defines the delivery guarantee. Commit before processing and a crash can lose records; commit after processing and a crash can repeat them. Spring Kafka commits after processing by default, so design listeners to tolerate duplicates.</p><h3>Part 1 takeaway</h3><p>A @KafkaListener method is the last step of a complete client-side workflow:</p><pre>Listener container  →  KafkaConsumer (one thread)<br>    ↓<br>hash(group.id) % 50  →  group coordinator<br>    ↓<br>JoinGroup / SyncGroup  →  partition assignment<br>    ↓<br>OffsetFetch  →  committed offset (or auto.offset.reset)<br>    ↓<br>FetchRequest per broker  →  buffer  →  max.poll.records<br>    ↓<br>Deserializer  →  @KafkaListener<br>    ↓<br>Offset commit (AckMode)  →  __consumer_offsets</pre><p>The group id decides who shares the work and where progress lives. The poll loop keeps the consumer in its group and must not be blocked for too long. The committed offset decides where reading starts, fetch settings decide how much data each round trip carries, and the moment we commit decides whether a crash loses or repeats records.</p><p>So far, we assumed that everything goes well, and that one consumer reads one topic. Real systems are less kind:</p><ul><li>What happens when a record cannot be deserialized, or the listener throws an exception?</li><li>How does one consumer read several topics, each with its own event type?</li><li>How do several consumers share the partitions of one topic, and who decides which consumer gets which partition?</li><li>What happens to the group when a consumer joins, leaves, or crashes?</li></ul><p>Part 2 answers all of them: error handling with retries and dead-letter topics, JSON type mapping for multiple topics, scaling with concurrency, the four partition assignment strategies, and eager versus cooperative rebalancing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=daaf91a97c89" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding MX Messages, Part 4: Read the Account with camt]]></title>
            <link>https://medium.com/@youssefelmessbahi/understanding-mx-messages-part-4-read-the-account-with-camt-bdd9e9503f6a?source=rss-573653523742------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdd9e9503f6a</guid>
            <category><![CDATA[banking]]></category>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[iso20022]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[payments]]></category>
            <dc:creator><![CDATA[YOUSSEF EL MESSBAHI]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 21:16:01 GMT</pubDate>
            <atom:updated>2026-11-02T20:18:20.026Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IKaDHZudc3lZRdlpm3Eurg.png" /></figure><h3>The payment message is not the bank account</h3><p>Atlas Components has submitted its supplier payments and received processing reports. Its treasury system still needs to answer another question: what actually appeared on its account? That question introduces the cash-management message family, commonly abbreviated camt.</p><p>The family is broader than statements. It includes account reporting, notifications, cancellation requests, and investigation-related messages. Grouping all camt messages under “payment confirmation” obscures their different jobs. A request to cancel a transfer and a statement containing a booked debit are both cash-management messages, but they establish fundamentally different facts.</p><p>This article follows Atlas’s illustrative CIH accounts. The domestic batch contains MAD 48,000 for Casablanca Metals at Banque Populaire, MAD 32,000 for Rif Logistics at Bank of Africa, and MAD 20,000 for Atlas Maintenance at Banque Populaire. In our partial-processing scenario, the first and third instructions execute and the second is rejected before booking. Separately, ATLAS-X01 instructs EUR 25,000 to Iberia Machines at European Bank E for invoice IM-2026–1042.</p><p>These fictional scenarios do not describe the real banks’ actual implementations, correspondent relationships, or reporting products. The domestic example makes no claim about the formats or interfaces of Moroccan clearing and settlement infrastructure. We use camt.052.001.08, camt.053.001.08, and camt.054.001.08 as explicit reporting versions for teaching.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5_4p809sFKn_q3_pQhZYLQ.png" /></figure><p><em>Figure 2. Instruction status, account reporting, and invoice settlement answer related but different questions.</em></p><h3>Three reporting messages, three useful perspectives</h3><p>camt.052, BankToCustomerAccountReport, provides account information from an account servicer to an account owner or an authorized recipient. It is commonly used for intraday reporting. The supported balances, entries, timing, and pending information depend on the reporting service. “Intraday” does not imply an unconditional real-time feed.</p><p>camt.053, BankToCustomerStatement, provides statement information about an account, including booked entries and balances. A common service produces it at the end of a reporting period, often a business day. The reporting agreement defines the actual period and delivery arrangements; the message name alone does not impose a universal midnight schedule.</p><p>camt.054, BankToCustomerDebitCreditNotification, notifies relevant debit or credit entries. It supports event-oriented account reporting without being a complete replacement for the account statement. A service may notify individual entries or package several entries, and its delivery timing must be understood from the agreement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YPMLJ5sdGKA1mSZ1EerSyw.png" /></figure><p><em>Figure 3. Choose the report for the question being asked; confirm the bank’s reporting contract.</em></p><p>For Atlas, a camt.052 can support liquidity monitoring during the day. A camt.054 can trigger timely processing of a new account entry. A camt.053 can support period reconciliation and balance continuity. These are complementary uses, not a requirement to post the same money three times.</p><p>The sender is the account servicer in these reporting relationships; the receiver is the account owner or an authorized recipient. An authorized treasury provider may receive a report without owning the account. A bank can also be an account owner at another bank, so “bank-to-customer” does not mean that the customer must be a non-bank corporation.</p><h3>Start with the account, currency, and reporting period</h3><p>Before reading individual entries, identify the account being reported. The business effect of a debit or credit depends on that account’s perspective. A debit on Atlas’s account and a credit on a correspondent’s account are not contradictory descriptions of one ledger. They describe different ledgers.</p><p>Our domestic example starts with a booked balance of MAD 150,000. D01 and D03 produce principal debits of MAD 48,000 and MAD 20,000. D02 produces no booked debit in this scenario. With no other entries or fees, the closing booked balance is MAD 82,000.</p><p>The separate EUR account starts at EUR 40,000. Its EUR 25,000 principal debit leaves EUR 15,000 before other entries. Never combine these balances into a single unqualified number. Consolidated liquidity reporting requires an explicit valuation currency, rate source, and timestamp.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UxnJ34tocFsWsDVC1pt4rg.png" /></figure><p><em>Figure 4. The partial-processing scenario books MAD 68,000, leaving MAD 82,000 from an opening MAD 150,000.</em></p><p>Booked balance and available balance are different concepts. Reservations, credit facilities, value dating, or other account rules can affect availability. A single field called balance is therefore inadequate for a treasury application. Preserve the balance type, amount, currency, debit/credit direction, date, and any relevant service context.</p><p>An account report can arrive before a customer status report, even when the underlying booking happened after processing acceptance. Arrival order across channels is not a reliable financial sequence. Use the report’s business dates and identifiers alongside receipt timestamps, and retain uncertainty when the information does not establish an exact sequence.</p><h3>Read the structure without flattening it too early</h3><p>The three reporting documents share recognizable concepts but use different containers: Rpt in camt.052, Stmt in camt.053, and Ntfctn in camt.054. Within the relevant structure, account and reporting information provide context for entries. Entry details can contain transaction details and references.</p><p>The entry level is important because one account booking need not correspond to one payment instruction. A batch debit can represent several underlying transactions. Conversely, one payment can generate principal and fee entries, or later reversals and returns. A parser that emits one payment per Ntry without considering details will eventually miscount.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uy31UwXo2FBQZ1m0v39Jzw.png" /></figure><p><em>Figure 5. Account context surrounds entries; entry details may explain several underlying transactions.</em></p><p>The following camt.053.001.08 excerpt illustrates a single booked principal debit for D01. It is an incomplete Ntry excerpt, not a standalone valid statement:</p><pre>&lt;Ntry&gt;<br>  &lt;NtryRef&gt;CIH-MAD-ENTRY-D01&lt;/NtryRef&gt;<br>  &lt;Amt Ccy=&quot;MAD&quot;&gt;48000.00&lt;/Amt&gt;<br>  &lt;CdtDbtInd&gt;DBIT&lt;/CdtDbtInd&gt;<br>  &lt;Sts&gt;&lt;Cd&gt;BOOK&lt;/Cd&gt;&lt;/Sts&gt;<br>  &lt;BookgDt&gt;&lt;Dt&gt;2026-10-19&lt;/Dt&gt;&lt;/BookgDt&gt;<br>  &lt;ValDt&gt;&lt;Dt&gt;2026-10-19&lt;/Dt&gt;&lt;/ValDt&gt;<br>  &lt;AcctSvcrRef&gt;CIH-ASR-D01&lt;/AcctSvcrRef&gt;<br>  &lt;BkTxCd&gt;&lt;Prtry&gt;&lt;Cd&gt;DEMO-TRANSFER&lt;/Cd&gt;&lt;/Prtry&gt;&lt;/BkTxCd&gt;<br>&lt;/Ntry&gt;</pre><p>The amount is positive; DBIT supplies its account direction. BOOK identifies the illustrated booked status. Booking date and value date are distinct fields even when they happen to be equal. DEMO-TRANSFER is an explicitly fictional proprietary code, not an ISO bank-transaction code or a real CIH code.</p><p>Bank transaction codes classify entries. They can be structured or proprietary, depending on the message and service. A proprietary value requires an agreed interpretation. Treating an unfamiliar value as “ordinary payment” can misclassify fees, interest, reversals, or non-payment entries.</p><h3>A notification is not another movement of money</h3><p>Suppose a camt.054 first reports the MAD 48,000 debit. Later, a camt.052 includes the same entry in an intraday report, and the camt.053 includes it in the statement. Atlas has one debit with several observations, not three debits totaling MAD 144,000.</p><p>This creates two different deduplication tasks. Transport deduplication avoids processing the same report twice. Economic-entry matching recognizes that different reports can describe the same account event. Solving only the first still leaves a treasury ledger vulnerable to double counting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HTwnpt-TrMT9d6wEKpRUHA.png" /></figure><p><em>Figure 6. Three observations can describe one account entry; reconcile them before updating economic totals.</em></p><p>An account-servicer reference may be valuable for matching, but its presence and uniqueness scope depend on the service. Other useful evidence includes account identity, entry reference, amount, currency, direction, booking date, transaction references, and statement context. Do not assume that every report supplies every field or preserves the same value in every position.</p><p>Build a matching policy with confidence levels. An exact, scoped account-servicer reference can support a strong match. Amount and date alone usually cannot: two suppliers can receive identical amounts on the same day. Ambiguous matches belong in an exception queue, not in an automatic “best guess” posting path.</p><h3>Batch booking changes reconciliation granularity</h3><p>In one teaching alternative, D01 and D03 appear as two debit entries of MAD 48,000 and MAD 20,000. In another, the bank books one MAD 68,000 entry with enough transaction detail to explain both accepted payments. These are alternative representations of the same accepted subset, not additional debits.</p><p>A batch-booking request in pain.001 does not guarantee a particular reporting layout. Confirm how the bank handles partial execution, fees, rejected items, and transaction details. A bank may offer a consolidated booking while providing detailed information through another report or channel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4YC154VqLZ3P5Yv9jsOrjQ.png" /></figure><p><em>Figure 7. Separate and consolidated booking can represent the same MAD 68,000 principal total.</em></p><p>Your reconciliation model should support one-to-many and many-to-one relationships. The payment instruction remains an object with its own identity; the account entry remains another object. A match relationship connects them with an allocated amount and evidence. Forcing both into one database row makes partial batches and separately booked charges unnecessarily difficult.</p><p>Check conservation at the appropriate level. The accepted domestic principal total is MAD 68,000. If the report contains a separate fee, do not allocate that fee to a supplier’s invoice principal merely to make totals balance. Record the fee according to its actual role and account treatment.</p><h3>From payment matching to invoice reconciliation</h3><p>Matching a bank entry to ATLAS-D01 answers which payment produced the entry. Matching that payment to invoice CM-2026–301 answers which business obligation Atlas intended to settle. These are related reconciliation steps with different evidence.</p><p>Structured remittance information can help the beneficiary allocate an incoming amount to invoices. Unstructured text can still be useful, but it may be truncated, normalized, or entered inconsistently. Store the original information and normalized search fields separately. Avoid deleting punctuation or leading zeros from invoice references without a documented rule.</p><p>For ATLAS-X01, Atlas can reconcile its EUR 25,000 debit to the supplier payment. That local reconciliation does not establish that Iberia’s receivable is cleared in Iberia’s accounting system. The supplier may need to receive funds and allocate them to IM-2026–1042. Bank credit and commercial allocation are themselves different events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wBBOUXBb2yLhND4ty45CUg.png" /></figure><p><em>Figure 8. Connect account entry, payment instruction, and invoice without treating their identities as interchangeable.</em></p><p>Missing references require controlled fallback. A service can compare amounts, currencies, parties, and dates, but should expose its confidence and reasons. Operators need to see why a match was proposed, approve exceptions, and reverse an incorrect match without deleting the original bank evidence.</p><h3>MT reporting comparisons are functional, not lossless</h3><p>MT940 is commonly associated with account statements, and MT942 with interim transaction reporting. MT900 and MT910 provide debit and credit confirmations respectively. These offer useful functional comparisons with camt.053, camt.052, and camt.054, but a comparison is not a universally reversible field mapping.</p><p>ISO 20022 can represent richer structured entry details, parties, references, balances, and remittance information. A translation may have to flatten structured data, omit unsupported information, or place it into narrative fields. Translating back cannot reliably reconstruct structure that was lost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pjArQ2xlyS0-LrckLJCijA.png" /></figure><p><em>Figure 9. Compare business functions first; assess mapping and information loss separately.</em></p><p>A migration therefore needs more than XML ingestion. Test actual bank samples, balance types, statement numbering, entry references, proprietary codes, and pagination. Compare economic results across both feeds during a controlled transition. Differences in presentation should not create new transactions, while genuine omissions must not be hidden by aggressive deduplication.</p><p>Do not equate every SWIFT MT message with ISO 15022. SWIFT MT is a broader family; ISO 15022 has a particular standards scope, notably in securities messaging. FIN is a messaging service, not another name for the semantic content of a bank statement.</p><h3>Cancellation starts with a request</h3><p>camt.055 is CustomerPaymentCancellationRequest. In the direct teaching case, Atlas sends a request to CIH concerning an earlier customer payment instruction. It identifies the original instruction and communicates the cancellation request. Sending it does not establish that the bank has stopped the payment.</p><p>camt.056 is FIToFIPaymentCancellationRequest. A bank uses it to request cancellation from the relevant financial-institution counterparty under the applicable process. It may be needed because the original instruction has already moved beyond the customer-facing bank’s unilateral control.</p><p>camt.029, ResolutionOfInvestigation, can communicate a resolution within the relevant investigation or cancellation process. Its meaning depends on the case, references, status, and usage rules. It is not simply a generic “refund successful” message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zG6_eNqLMUBiGxvIa-zzSA.png" /></figure><p><em>Figure 10. A customer request, an interbank request, and an investigation response have separate senders and purposes.</em></p><p>For an alternative ATLAS-X01 scenario, Atlas discovers an error before release. CIH may be able to stop the instruction locally and release a reservation. If the instruction is already with another bank, the outcome depends on its state and the applicable process. If funds have settled or been credited, recovery can require further cooperation and a return of funds.</p><p>There is no universal guarantee that a beneficiary will consent or that a bank can recover funds. Avoid promising cancellation merely because the API accepted the request. Present “cancellation requested” until evidence supports a more definitive result.</p><h3>A return needs its own financial evidence</h3><p>pacs.004, PaymentReturn, carries a return of funds in the applicable interbank flow. It refers back to the original payment and describes the return, including relevant amounts, agents, references, and reason information. It is a new financial message related to the original transfer, not an edit that makes the original transfer disappear.</p><p>In a simplified full-return alternative, the EUR 25,000 principal returns without fees or FX. Atlas’s illustrative EUR balance moves from EUR 15,000 back to EUR 40,000 when the return is booked. Those equal amounts are teaching assumptions. Real return amounts and timing can differ, and any fees or FX consequences must be handled explicitly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jOo1-qsU92R5R06qNs-26A.png" /></figure><p><em>Figure 11. The return creates new evidence and a new account entry while preserving the original debit history.</em></p><p>A positive cancellation-related response is not a substitute for reconciling the actual funds and account posting. Conversely, a returned credit may arrive while an investigation workflow is still awaiting administrative closure. Keep case management and ledger evidence linked but independently observable.</p><p>The cancellation case needs its own identifier, separate from ATLAS-X01. It also needs enough original-message and transaction references for the receiving party to find the instruction. Assignment or case references, original message identification, original payment identification, and cancellation reasons serve different roles in the relevant message structures. A case identifier should not replace the original EndToEndId in the payment record.</p><p>For a return, retain its own message and return identifiers as well as the original payment references. Compare returned amounts and currencies with the original obligation, but do not require equality as a universal rule. A partial return is still related to the same original payment; it is not evidence that the original amount was smaller. Represent the relationship and outstanding difference explicitly.</p><p>This is also why a cancellation endpoint should not directly reverse a booked debit. A request can be rejected, become too late, or require a downstream response. Posting a refund at request time can give the customer spendable funds while the original payment remains effective. The authorization to post, the funding evidence, and the case outcome need a controlled relationship.</p><p>The original payment can remain historically settled, with a related return subsequently settled and credited. A single terminal state called cancelled cannot express that history accurately. Use relationships between the original payment, cancellation case, return payment, and account entries.</p><h3>Make reconciliation a durable service</h3><p>The ingestion boundary should preserve raw reports, verify the expected sender and account entitlement, validate the selected schema and reporting profile, and extract entries without losing their context. Normalize amounts with exact decimal arithmetic and retain currency and direction. Never use binary floating point for account totals.</p><p>Persist a report inbox and processing outcome atomically. Store statement identity, sequence and pagination information when supplied. A statement that arrives in several parts must not be treated as complete after the first part merely because its XML is valid. Missing pages and duplicated pages require different responses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UjweC6D_x1o1nvzBlPoLdA.png" /></figure><p><em>Figure 12. Preserve evidence, normalize carefully, match explicitly, and route unresolved differences to operators.</em></p><p>Balance checks are powerful but scoped. Opening balance plus signed booked entries should reconcile to the corresponding closing balance when the report supplies a complete, compatible set. That equation is not valid if you mix available and booked balances, different currencies, or incomplete reporting periods.</p><p>Corrections and reversals deserve explicit handling. An entry may carry a reversal indicator, and later reports may supplement information about an earlier entry. Do not implement every later appearance as a new debit, and do not negate an amount solely because a narrative contains the word “reversal.” Interpret the structured direction, reversal information, entry identity, and bank reporting rules together. Preserve both the original observation and the correction so an operator can reconstruct the account history.</p><p>For period close, keep a completeness record alongside the calculated balance. It should identify which statement or pages were received, whether the previous period’s closing balance agrees with this period’s opening balance, and which differences remain unresolved. A mathematically balanced subset is not necessarily a complete statement. Missing one debit and one equal credit can leave the balance unchanged while concealing two missing transactions.</p><p>Focused tests should include a repeated notification, the same entry later appearing in a statement, a consolidated batch booking, two equal-value payments with ambiguous references, a separately booked fee, and a return that arrives after the original payment was marked settled. These cases test the actual economic model, not just XML parsing.</p><p>Audit access and retention matter because account reports expose sensitive financial information. Keep raw payloads out of routine logs, restrict download permissions, and record operator decisions. An exception queue should show the mismatch, the evidence, its age, and an accountable owner.</p><p>The result is a payment platform that can explain its conclusions. It knows which instruction was accepted, which account was debited, which leg settled, which credit was observed, and which business obligation was matched. Where evidence is missing, it preserves that uncertainty instead of turning it into a misleading green checkmark.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdd9e9503f6a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding MX Messages, Part 3: What Payment Status Really Proves]]></title>
            <link>https://medium.com/@youssefelmessbahi/understanding-mx-messages-part-3-what-payment-status-really-proves-2c1ddd17184f?source=rss-573653523742------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c1ddd17184f</guid>
            <category><![CDATA[iso20022]]></category>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[banking]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[payments]]></category>
            <dc:creator><![CDATA[YOUSSEF EL MESSBAHI]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 19:16:01 GMT</pubDate>
            <atom:updated>2026-11-02T20:15:36.707Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ItPfgRINZD5Gnslp38PRUg.png" /></figure><h3>The most expensive boolean in a payment application</h3><p>A payment screen displays “Success.” The customer reads it as “my supplier has the money.” The developer meant “the request reached our server.” The operations team understands it as “our outbound gateway accepted the message.” All three interpretations can exist while the same payment is still unresolved.</p><p>The problem is not poor wording alone. It is a data-model problem: several independent facts have been compressed into one boolean. A payment integration needs to distinguish local submission, technical delivery evidence, business acceptance, interbank settlement, and beneficiary-account credit. Each fact has a source and scope.</p><p>We continue with Atlas Components in Casablanca and its illustrative sending bank, CIH. A domestic MAD batch contains ATLAS-D01 for MAD 48,000 to Casablanca Metals at Banque Populaire, ATLAS-D02 for MAD 32,000 to Rif Logistics at Bank of Africa, and ATLAS-D03 for MAD 20,000 to Atlas Maintenance at Banque Populaire. Its message reference is ATLAS-MAD-20261019–01 and its payment-information reference is ATLAS-SUPPLIERS-MAD.</p><p>A separate cross-border instruction, ATLAS-X01, pays EUR 25,000 to Iberia Machines at fictional European Bank E for invoice IM-2026–1042. These scenarios do not describe the named banks’ real implementations, correspondent relationships, or reporting services. In particular, the domestic example does not assert that a Moroccan clearing system uses the messages shown here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*prZvp0_avpSPn4YJRUfTlg.png" /></figure><p><em>Figure 2. Delivery, acceptance, settlement, and credit answer different questions.</em></p><h3>pain.002 and pacs.002 look in different directions</h3><p>pain.002 is CustomerPaymentStatusReport. Its business role is to report the status of an initiation instruction to the relevant preceding party. In the direct corporate scenario, CIH sends it to Atlas in response to the pain.001 relationship. It can report positive, negative, or pending information when supported by the agreed service. Its existence does not mean every bank sends every possible positive status at every stage.</p><p>pacs.002 is FIToFIPaymentStatusReport. It reports the status of an interbank payment instruction between financial institutions. In a simple direct route, European Bank E can report to CIH about the instruction it received. In an alternative serial route through European Bank F, reports relate to the relevant preceding instruction and parties on each leg.</p><p>This is a business distinction, not just a difference in XML prefixes. A bank may consume an interbank report and produce a customer report using its own evidence and contractual reporting rules. Blindly relabeling pacs.002 as pain.002 loses the boundary between what the bank has learned and what it is authorized or able to tell its customer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2kCwHfBeS_nfFehvjqb9dA.png" /></figure><p><em>Figure 3. Customer reporting and interbank reporting refer to related instructions at different boundaries.</em></p><p>In a relay arrangement, a forwarding bank sits between the initiating customer and the debtor agent. Reporting duties follow that arrangement. The debtor agent is not the only institution that can ever send a pain.002. Likewise, “pain” does not mean that every exchange carrying it must physically connect a corporation directly to a bank.</p><p>Both reports establish the sender’s reported status within the identified scope. Neither is a general-purpose bank statement. A customer status report is not itself a ledger entry, and receiving a pacs.002 does not independently execute a debit or credit in the receiving application.</p><h3>Technical acknowledgment is a separate evidence stream</h3><p>A transport acknowledgment says something about processing within the relevant messaging service. Its exact meaning depends on the service and response. It must not be promoted into business acceptance by the next bank merely because it arrived quickly and contains a positive indicator.</p><p>Similarly, an HTTP 200 from your own API can mean only that your service accepted a request for processing. If the API offers asynchronous execution, return a durable operation identifier and a precise state such as received or queued. Make the distinction visible in the product as well as in the code.</p><p>Imagine the outbound message for ATLAS-X01 passes a network-level validation, but European Bank E later rejects it because the instructed account information is unusable. The technical acknowledgment and the business rejection are not contradictory. They concern different stages and different validators.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*00ap-L3-TznyjnPU08FFpg.png" /></figure><p><em>Figure 4. A positive transport result can coexist with a later business rejection.</em></p><p>Store these events separately. Overwriting a field called status first with ACK and later with RJCT destroys useful information about how far the message traveled. An operator investigating a dispute needs both facts, including their timestamps, identifiers, and sources.</p><h3>Scope comes before the status code</h3><p>A pain.002 can carry original group information, original payment-information details, and transaction-level status information, subject to the version and usage rules. Those levels correspond to different scopes. A group-level rejection is not the same event as a rejection of one transaction in an otherwise accepted group.</p><p>For the MAD batch, the original message reference identifies the incoming submission. The original payment-information reference identifies the supplier group. The original transaction references identify D01, D02, or D03. An application should resolve that scope before applying any reported status.</p><p>Our teaching outcome is deliberately mixed: D01 and D03 are accepted for further execution; D02 is rejected before execution because of a fictional account-data problem. The total submitted amount remains MAD 100,000. The accepted subset is MAD 68,000 and the rejected subset is MAD 32,000. Acceptance here does not mean either accepted supplier has already received credit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bmDCSqQBjq5l0Ltcr5fa4Q.png" /></figure><p><em>Figure 5. The batch retains its original total while transaction outcomes split into distinct subsets.</em></p><p>Whether a bank offers partial processing or an all-or-nothing service is a contractual and implementation question. The existence of transaction-level status elements does not prohibit a bank from offering an atomic batch product. Conversely, an ERP must not assume that every batch is atomic simply because it was submitted in one file.</p><p>A partial result creates a practical resubmission rule: repair and resubmit only the rejected obligation, under the bank’s duplicate and reference rules. Resending the original three transactions can duplicate the two that were already accepted. A corrected submission is a new processing attempt linked to the same business obligation, not a reason to erase the first attempt’s audit history.</p><h3>Codes are precise only with context</h3><p>Common status codes include RCVD for receipt, ACTC for accepted technical validation, ACCP for acceptance after technical validation and customer-profile checks, ACSP for accepted settlement in process, PDNG for pending, and RJCT for rejected. The precise availability and conditions belong to the selected message usage and service.</p><p>ACCP should not be described as “the XML parsed.” Its scope is broader than that. It should also not be described as proof of completed settlement. Both interpretations create production defects: one understates the evidence; the other overstates it.</p><p>ACSC and ACCC require especially careful handling. Settlement-completion and creditor-credit confirmation concepts cannot be treated as interchangeable labels for a universal terminal success state. Determine which code the profile permits, what the reporting party is confirming, and which account or leg that confirmation concerns.</p><p>As a concrete example of why the profile matters, the UK Open Banking payment-status model distinguishes ACSC as completion on the debtor-account side and ACCC as completion on the creditor-account side. That is useful evidence about that model, not permission to impose its complete state machine on every interbank exchange. A bank’s CBPR+ integration must use the definitions and reporting conditions of its applicable release and service. The question to ask is not simply “is this a completed code?” but “which completion is this sender asserting for this instruction?”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ly57hz83EH-sclQxWVrmkQ.png" /></figure><p><em>Figure 6. A useful status assertion includes source, scope, code, and event time.</em></p><p>There is no promise that a payment will produce a neat sequence of RCVD, ACTC, ACCP, ACSP, and a final code. Some services send only exceptions. Some combine stages. Some reports arrive late or are delivered twice. A state machine that requires every intermediate code can leave a successfully processed payment stuck forever.</p><p>External code lists also have a lifecycle separate from the XML schema. A base XSD may constrain the lexical form of a code without enumerating every currently permitted business value. Keep supported code lists and profile rules versioned; do not assume successful XSD validation proves that an externally defined code is valid for the exchange.</p><h3>Correlation needs more than one identifier</h3><p>For the incoming MAD instruction, MsgId identifies the customer message and PmtInfId identifies its supplier group. EndToEndId identifies the customer’s individual payment reference. A status report has its own message identity and references the original instruction using the relevant original-reference fields.</p><p>The report’s own MsgId must not replace the payment’s customer MsgId. They identify different objects. Likewise, an EndToEndId can be useful for matching without being a globally unique database key across every customer, account, and year.</p><p>The following pain.002.001.10 excerpt illustrates original-reference correlation. It is incomplete and is not a valid standalone document:</p><pre>&lt;OrgnlGrpInfAndSts&gt;<br>  &lt;OrgnlMsgId&gt;ATLAS-MAD-20261019-01&lt;/OrgnlMsgId&gt;<br>  &lt;OrgnlMsgNmId&gt;pain.001.001.09&lt;/OrgnlMsgNmId&gt;<br>&lt;/OrgnlGrpInfAndSts&gt;<br>&lt;OrgnlPmtInfAndSts&gt;<br>  &lt;OrgnlPmtInfId&gt;ATLAS-SUPPLIERS-MAD&lt;/OrgnlPmtInfId&gt;<br>  &lt;TxInfAndSts&gt;<br>    &lt;OrgnlEndToEndId&gt;ATLAS-D02&lt;/OrgnlEndToEndId&gt;<br>    &lt;TxSts&gt;RJCT&lt;/TxSts&gt;<br>  &lt;/TxInfAndSts&gt;<br>&lt;/OrgnlPmtInfAndSts&gt;</pre><p>The absence of a reason in this short excerpt is intentional; a production usage may require reason information. Store structured reason codes, additional information, and the reporting party where supplied. Free text is useful to operators but is a poor primary key for automated recovery logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b-yOPBJe63ATXtMusoffzA.png" /></figure><p><em>Figure 7. A report has its own identity and points back to the instruction it describes.</em></p><p>Resolve reports against a composite context: sender, service, original message identity, original message type, and available payment references. If that process produces two candidates, quarantine the event for investigation. Choosing the first database row can incorrectly reject or complete another customer’s payment.</p><p>Original-reference fields can also be absent or insufficient. A malformed submission may fail before a receiver can trust its message identity. Such an error may need a channel-level response linked to an upload or operation ID rather than an invented transaction status. Keep the transport operation and the business message as separate records so that this failure remains explainable.</p><p>For the international example, the pacs.002 companion fixture references CIH-X01-MSG1, the original pacs.008 message type, CIH-X01-LEG1, ATLAS-X01, CIH-TX-X01, and the original UETR. It reports PDNG for that identified transaction. The fixture demonstrates available correlation evidence; it does not claim every community requires all those references or that a pending report must contain exactly this subset.</p><p>Status reasons also require scope. A reason concerning an account problem should lead to a controlled repair process, not an automatic replacement account selected by software. A compliance-related reason may intentionally disclose limited information. Preserve the received value, restrict sensitive details appropriately, and map it to a customer-facing explanation without fabricating a more specific cause.</p><h3>Rejection, return, and cancellation are different events</h3><p>A rejection says that an instruction is not accepted or will not proceed within the relevant processing scope. A return involves sending funds back after the relevant settlement has occurred. A cancellation request asks another party to stop or undo processing where possible. None of these terms should be a synonym for the others.</p><p>For the rejected D02 teaching case, no customer debit has been booked and no relevant interbank settlement has occurred. The application can release any temporary reservation according to its own accounting controls. There is no incoming return of MAD 32,000 to invent.</p><p>For an alternative EUR case, suppose the relevant settlement has occurred and funds later need to be returned. The appropriate payment-return flow uses pacs.004 under its applicable rules. A status event alone is not an instruction to add EUR 25,000 to Atlas’s balance. The bank must reconcile the return and post the resulting account entry through its ledger controls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uCQVl0cNk0B_OmrxVRp3hg.png" /></figure><p><em>Figure 8. Use the relevant leg’s settlement state to understand why a rejection and a return have different financial consequences.</em></p><p>This distinction is especially important in longer chains. One bank’s leg can be settled while another part of the route is unresolved. Do not infer a universal “before settlement” condition merely because your local system has not received a completion report. Absence of evidence is not evidence that no money moved.</p><h3>Model evidence, then derive operational state</h3><p>A robust design stores immutable received events and derives the current operational view. An event includes raw-message provenance, sender, reception time, reported event time when available, correlation outcome, status scope, reason, and processing decision. The raw XML and the normalized event should be linked, not treated as interchangeable records.</p><p>The projection might distinguish instruction acceptance, delivery outcome, settlement evidence, customer debit, and beneficiary-credit evidence. These dimensions can be summarized for users, but the underlying facts must remain separate. “Accepted; beneficiary credit not yet confirmed” is often a more honest product state than “Success.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kE7O-EXQKRg9rmeo8OI42Q.png" /></figure><p><em>Figure 9. Several evidence dimensions support one user-facing view without collapsing their meanings.</em></p><p>Out-of-order delivery requires a transition policy. A delayed receipt report must not overwrite a later rejection. A later return must not erase the historical fact that the original payment settled. Conflicting reports should create an exception with preserved evidence rather than trigger arbitrary last-write-wins behavior.</p><p>Idempotency belongs at the event boundary as well. Persist an inbox record with a durable deduplication key in the same transaction as the projection update. Prefer reliable message identifiers within their sender and service context. Where the service can resend the same business event under a new envelope, use an additional business-event fingerprint carefully, so legitimate updates are not discarded as duplicates.</p><h3>A timeout is an unresolved question</h3><p>Suppose Atlas’s submission times out before it receives a response. The ERP does not know whether CIH accepted the instruction. A new submission with newly generated references may bypass duplicate controls and produce a second payment. The correct recovery depends on the channel’s agreed idempotency and inquiry mechanisms.</p><p>The same uncertainty exists between banks and within an integration platform. Distinguish a definite local validation rejection from an unknown remote outcome. A retry policy that treats both as a generic exception is too coarse for payments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sM3svNseoCwSFyAlEOX8Mw.png" /></figure><p><em>Figure 10. Recover the existing operation’s outcome before deciding whether a new instruction is needed.</em></p><p>Operationally, uncertain items need ownership and aging. Record when the uncertainty began, which inquiries or reconciliation checks have run, and what evidence would resolve it. A queue that endlessly retries without an owner can remain technically healthy while accumulating duplicate-payment risk.</p><p>Service-level monitoring should therefore track unmatched reports, conflicting statuses, pending items beyond expected processing windows, and uncertain delivery outcomes. The expected windows are service-specific. Hardcoding a universal number of minutes into a generic ISO library confuses message processing with an actual bank’s service commitment.</p><h3>Test the transitions that can move money twice</h3><p>Consider a consumer receiving a pain.002 while its database is temporarily unavailable. Acknowledge the transport message only after durable processing, or use the equivalent recovery mechanism supported by that channel. If the system updates a payment and crashes before recording that the report was processed, redelivery must not trigger the same ledger action again. Better still, keep status ingestion separate from any financial posting command and make each command independently idempotent.</p><p>A focused test suite should deliver the same report twice, deliver a receipt after a rejection, and deliver a report whose original reference matches two candidate records. Expected results are one effective update, no regression of the stronger evidence, and an explicit correlation exception. Another test should provide transaction outcomes without a synthetic group status; the application must still derive the accepted and rejected subsets correctly.</p><p>Test the user interface as well. A customer should be able to distinguish D02’s repairable rejection from D01’s accepted execution and from an unrelated payment with an unknown delivery outcome. The available actions should follow that distinction. “Retry all” is inappropriate when the batch already contains accepted transactions; “cancel” should create a cancellation workflow rather than delete the payment record.</p><p>These behaviors are architecture decisions surrounding the messages. ISO 20022 supplies a language for exchanging facts, but it cannot guarantee that an application applies those facts safely. The integration is complete only when duplicate delivery, missing evidence, partial results, and human recovery have defined behavior.</p><h3>Reconcile the report with account evidence</h3><p>After D01 and D03 execute in our domestic teaching outcome, Atlas expects principal debits totaling MAD 68,000. Whether those appear as one batch booking or separate entries depends on the agreed booking behavior. The rejected D02 remains an unpaid obligation that can be corrected and resubmitted separately.</p><p>A pain.002 helps explain the instruction’s processing. A camt account report or statement helps explain what appeared on a particular account. Matching the two can reveal a missing debit, an unexpected fee, an incorrect duplicate, or a booking that arrived before the final status report.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uj1e01lNZOX3kVmdW1saZw.png" /></figure><p><em>Figure 11. Status and account reporting complement each other; neither should silently replace the other.</em></p><p>In the separate EUR case, an Atlas debit at CIH does not prove an Iberia credit at European Bank E. A credit report for a correspondent account likewise concerns that correspondent account. Always ask whose account the report describes before using it to close a business obligation.</p><p>The next article develops this account perspective using camt.052, camt.053, and camt.054. It also follows cancellation and return messages, where a request, a response, and an actual movement of funds must remain distinct.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u4HxUsGvULBQhgQChMkzlA.png" /></figure><p><em>Figure 12. A useful payment view shows the strongest supported fact and the next unresolved question.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c1ddd17184f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding MX Messages, Part 2: How a Bank Builds pacs.008]]></title>
            <link>https://medium.com/@youssefelmessbahi/understanding-mx-messages-part-2-how-a-bank-builds-pacs-008-4bbf2e77f979?source=rss-573653523742------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bbf2e77f979</guid>
            <category><![CDATA[iso20022]]></category>
            <category><![CDATA[payments]]></category>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[banking]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[YOUSSEF EL MESSBAHI]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 17:16:02 GMT</pubDate>
            <atom:updated>2026-11-02T20:12:30.067Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Ak17GweyrUNBIT49mUlgQ.png" /></figure><p>Atlas Components, a manufacturer in Casablanca, asks CIH Bank to pay EUR 25,000 to its fictional supplier Iberia Machines at European Bank E. The customer reference is ATLAS-X01 and the invoice is IM-2026–1042. We assume sufficient EUR funds and an agreed execution date of 19 October 2026. These scenarios are fictional and do not describe the named banks’ actual systems, accounts, or correspondent relationships.</p><p>The pain.001 received from Atlas expresses what the customer wants. A pacs.008 expresses a financial institution’s customer credit transfer instruction to another financial institution. Producing the second requires decisions that the customer may neither know nor control: the next instructed agent, the relevant interbank account relationship, the settlement arrangement, and the identifiers needed to operate that leg.</p><p>This is why “convert pain.001 to pacs.008” is an incomplete requirement. Some data can be carried forward. Some must be enriched. Some belongs only to the customer channel. Other data becomes available only after routing and funding decisions. A syntactically successful converter can still produce an instruction that no bank can execute.</p><p>The aim here is to understand that construction boundary. We use pacs.008.001.08 for examples and pain.001.001.09 for the incoming fixture. These are explicit teaching versions, not an assertion about the version currently required by a particular service. A production deployment must select the version and usage guideline required by its receiving community.</p><h3>Separate the business instruction from its transport</h3><p>ISO 20022 defines business messages and their data structures. A particular scheme or usage guideline narrows how those structures may be used. A messaging service transports messages under its own rules. A settlement arrangement determines how the financial obligation between institutions is discharged. These layers interact, but they answer different questions.</p><p>FIN is associated with the traditional SWIFT MT messaging environment. FINplus supports ISO 20022 exchanges under applicable services and usage rules. CBPR+ provides usage rules for relevant cross-border payment and reporting exchanges; it is not itself the account on which banks settle. An MX document is therefore not a receipt for a movement of central-bank or correspondent money.</p><p>For an exchange that uses a Business Application Header, the AppHdr identifies application-level participants and message metadata. The Document carries the business message. A network envelope may add transport-specific information outside both. The application header is not the pacs.008 Group Header, and sender information in a transport envelope is not automatically identical to the debtor’s bank in every chain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7qjCrS6oZEGAOMQyBFsN5A.png" /></figure><p><em>Figure 2. The application header and business document have different responsibilities.</em></p><p>The pacs.008 Document contains FIToFICstmrCdtTrf, with a Group Header and credit-transfer transaction information. The generic ISO model and a concrete profile can have different repetition constraints. Never infer that a bank can place an arbitrary number of transfers into a CBPR+ message just because a base schema contains a repeating transaction element.</p><h3>Build a payment record before building an outgoing message</h3><p>A useful implementation starts by retaining the original instruction and constructing a bank-owned payment record. That record is not another ISO standard. It is an internal model that allows channel-specific details to coexist with routing, booking, compliance decisions, and lifecycle events.</p><p>Suppose Atlas submits a batch containing three domestic supplier payments: MAD 48,000, MAD 32,000, and MAD 20,000. One incoming file may create three payment records. They can share a customer batch reference while having different validation results and eventual routes. This does not establish which Moroccan infrastructure carries them. We deliberately make no domestic clearing-interface or message-format assumption.</p><p>The EUR 25,000 payment is a separate instruction, not a fourth item in that MAD batch. Keeping it separate prevents an example of currency conversion from silently changing the domestic control sum of MAD 100,000.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5dKg4-CHwzGL9JNNzh5BbQ.png" /></figure><p><em>Figure 3. An internal payment record preserves customer lineage while allowing transaction-specific decisions.</em></p><p>An internal record should preserve the original customer value alongside any normalized or corrected value. If a bank enriches a creditor-agent identifier using maintained reference data, record where that value came from. If an operator changes an address, preserve the original and the authorization for the change. Otherwise, the outgoing message may be reproducible only by guessing what the system knew that day.</p><p>A canonical model also needs extension points. Flattening every scheme-specific instruction into one free-text field makes the model easy to draw and difficult to operate. Conversely, exposing an entire generated XML object tree throughout the application couples business services to a message version. The boundary is an engineering choice: stable internal concepts, explicit scheme-specific data, and versioned adapters are often a practical compromise.</p><h3>Validation is a collection of different questions</h3><p>Parsing asks whether software can interpret the input. XML Schema validation checks structure, order, cardinality, and schema-defined types. Usage-guideline validation checks the narrower rules of the chosen exchange. Business validation checks whether this particular customer and bank can perform this particular payment.</p><p>These checks are not interchangeable. A well-formed XML file can have the wrong namespace. A schema-valid file can use a field that a profile forbids. A profile-valid payment can be unauthorized or unfunded. A correctly authorized instruction can still require investigation before release.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SvzqEqV0YATWTPz2izBk_A.png" /></figure><p><em>Figure 4. Each validation layer answers a different question; passing one does not imply passing the others.</em></p><p>For Atlas, business checks might include whether the submitting identity can instruct the account, whether duplicate submission rules permit this request, whether the execution date is acceptable, and whether funds or an approved credit arrangement are available. Compliance controls and the response to a match depend on the bank’s obligations and policy. Neither ISO 20022 nor a Java parser defines those decisions.</p><p>There is no universal requirement to postpone constructing every draft pacs.008 until all checks finish. A system may create a draft for inspection or enrichment. What matters is controlling release, versioning the decision evidence, and preventing a draft from being mistaken for an authorized outgoing instruction.</p><h3>Routing decides which leg the message describes</h3><p>Start with a deliberately simple route: CIH instructs European Bank E directly for the EUR 25,000 customer transfer. In a different, explicitly alternative serial route, CIH instructs European Bank F, which then instructs European Bank E. These diagrams describe different ways to execute ATLAS-X01; they are not two payments to send together.</p><p>In the serial route, each bank must identify the party it is instructing on its leg. Customer roles such as debtor and creditor remain meaningful across the chain, while instructing and instructed agents change. Intermediary-agent information describes relevant institutions in the payment path, subject to the selected profile’s rules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DVwJkO0wu12WzIja7D1T3g.png" /></figure><p><em>Figure 5. Choose one route. Hop-specific agents change without creating a second customer obligation.</em></p><p>The creditor account alone does not tell the application everything about routing. Account and bank identifiers require supported reference data and scheme rules. Treating a BIC as a substring to extract from an IBAN will fail across countries and account conventions. Treating every creditor-agent value supplied by a customer as already verified will fail for different reasons.</p><p>A route decision should therefore produce structured evidence: selected next agent, applicable service, settlement arrangement, relevant accounts, currency, and rule version. A payment message adapter consumes this result. It should not discover correspondent relationships through hardcoded string conditions scattered through XML setters.</p><h3>Settlement methods describe arrangements, not global completion</h3><p>The Group Header settlement information helps describe how the relevant interbank settlement is arranged. Common settlement-method codes include INDA, INGA, CLRG, and COVE. Their meaning must be read in the context of the message and applicable rules.</p><p>With INDA, settlement is by the instructed agent; with INGA, it is by the instructing agent. CLRG indicates settlement through a clearing system. COVE identifies a cover arrangement. These are not four levels of progress, and choosing COVE does not itself cause a cover payment to exist.</p><p>In a cover arrangement, the customer-transfer instruction and the interbank funding follow related paths. A pacs.008 carries the customer-transfer instruction toward the beneficiary bank; the cover funding is represented using the appropriate pacs.009 COV usage. The receiving bank must reconcile the instruction with its funding according to the arrangement. A duplicate customer transfer is not the correct way to “add the cover.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pGAMom0Mf3sYXIyiK_vElQ.png" /></figure><p><em>Figure 6. A cover alternative separates customer-transfer information from the related interbank funding path.</em></p><p>This article does not attempt a field guide to pacs.009. Its role here is to prevent a dangerous simplification: a direct customer instruction can coexist with an indirect funding path. Designing reconciliation around a single arrow from sender to beneficiary hides that dependency.</p><p>Likewise, a settlement event on one leg does not establish that Iberia Machines has an available credit. A receiving bank may still have posting work, account restrictions, or investigation to resolve. Keep interbank settlement and customer-account credit as distinct facts.</p><h3>Trace the source of every important field</h3><p>An account-based settlement example makes INDA easier to understand. Assume, solely for this direct-route teaching case, that CIH holds a EUR account serviced by European Bank E. From CIH’s perspective it is an asset held with another institution; from Bank E’s perspective it is a liability to CIH. When Bank E settles an accepted instruction by debiting that account, its liability to CIH decreases. A subsequent credit to Iberia’s account increases Bank E’s liability to Iberia. The institution may use internal clearing accounts and separate posting stages between these events.</p><p>The corresponding CIH accounting must also recognize the customer debit and the change in its asset with the correspondent. A typical teaching view is a reduction in CIH’s liability to Atlas and a reduction in its asset at Bank E, possibly through intermediate accounts. This is a balance-sheet explanation, not a prescribed journal template or posting sequence for the real banks. Reconciliation verifies that the bank’s internal representation agrees with the account servicer’s evidence.</p><p>The key distinction is between an instruction to perform these actions and the actions themselves. Serializing INDA does not debit a correspondent account. Dispatching pacs.008 does not independently synchronize both banks’ ledgers. The selected account relationship, authorization, liquidity, processing, and reporting make the instruction financially meaningful.</p><p>The outgoing message combines several categories of data. Debtor, creditor, remittance information, and EndToEndId often originate in the customer instruction. Bank-generated message and transaction references come from the bank’s own processing. Settlement information and interbank amounts depend on the chosen arrangement. Agent data may combine customer input and bank enrichment.</p><p>This provenance matters when an operator asks why an outgoing field differs from the incoming file. A mapper should make that answer inspectable. “The converter did it” is not an adequate audit explanation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MfCYcykmhTm5ciQ4OqTa6A.png" /></figure><p><em>Figure 7. Customer data, bank decisions, and routing data meet at a controlled construction boundary.</em></p><p>The following is an excerpt from the transaction portion of pacs.008.001.08. It omits required surrounding elements and is not a complete valid message. It illustrates the no-FX teaching case, before any fee deductions:</p><pre>&lt;PmtId&gt;<br>  &lt;InstrId&gt;CIH-X01-LEG1&lt;/InstrId&gt;<br>  &lt;EndToEndId&gt;ATLAS-X01&lt;/EndToEndId&gt;<br>  &lt;TxId&gt;CIH-TX-X01&lt;/TxId&gt;<br>  &lt;UETR&gt;9a4f0b64-204c-4c78-aee4-918b79f52d10&lt;/UETR&gt;<br>&lt;/PmtId&gt;<br>&lt;IntrBkSttlmAmt Ccy=&quot;EUR&quot;&gt;25000.00&lt;/IntrBkSttlmAmt&gt;<br>&lt;InstdAmt Ccy=&quot;EUR&quot;&gt;25000.00&lt;/InstdAmt&gt;<br>&lt;ChrgBr&gt;SHAR&lt;/ChrgBr&gt;</pre><p>InstrId identifies an instruction between relevant parties. EndToEndId links the payment to the initiating party’s reference. TxId and UETR have different identification roles; a UETR provides a standardized unique reference used for tracking in applicable flows. The references should be mapped and preserved according to the selected usage rules, rather than regenerated indiscriminately at each boundary.</p><p>A UETR can originate upstream, including in supported corporate flows. Creating a UUID locally does not register a payment with a tracking service or prove that another institution has received it. Tracking is a system interaction governed by the applicable service, not a side effect of serializing an XML element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*olSKb1LfZ6S_6hBGcg9oIw.png" /></figure><p><em>Figure 8. Preserve payment lineage while keeping message and instruction identities scoped to their purpose.</em></p><h3>Amounts describe different financial facts</h3><p>InstdAmt expresses the instructed amount before charges according to its message definition. IntrBkSttlmAmt expresses the amount for the relevant interbank settlement. The customer debit, interbank amount, charges, and beneficiary credit need not all be equal. Equality in our fee-free teaching fixture is an assumption chosen to make the flow readable.</p><p>Consider a separate FX alternative for the same EUR 25,000 obligation: Atlas funds the payment from MAD at an explicitly hypothetical rate of EUR 1 = MAD 10.80. The principal conversion is MAD 270,000 before fees. This does not change the EUR invoice amount, and it does not establish a real bank quote or Moroccan exchange-control treatment.</p><p>The internal payment record needs to retain the quote direction, rate, currencies, principal, charges, and rounding policy as applicable. A bare decimal called exchangeRate is insufficient. Reversing the direction can produce a numerically plausible but financially disastrous debit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ky4CaLuSzYewXIT1Y0S5tw.png" /></figure><p><em>Figure 9. The same payment can have several amount facts; never sum or compare them without their roles and currencies.</em></p><p>From a ledger perspective, a bank may reserve funds before posting, post before dispatch, or use other controlled sequences. These are implementation and account-contract choices, not a universal XML timeline. Model reservations, booked debits, settlement postings, and reversals explicitly. A message object should never be the only record that explains why an account balance changed.</p><p>For the illustrative EUR account, an opening balance of EUR 40,000 and a booked principal debit of EUR 25,000 produce EUR 15,000 before other entries. That arithmetic proves something about Atlas’s account in the example. It says nothing by itself about the balance of Iberia Machines at another bank.</p><h3>A small Java boundary that tells the truth about its limits</h3><p>The companion project uses Java 21, Spring Boot, and Prowide ISO 20022. Prowide Core is the MT-oriented library; the MX model belongs to the ISO 20022 library. Neither library supplies a bank’s SWIFT connection, correspondent accounts, or settlement engine.</p><p>The example deliberately exposes an inspection endpoint rather than a live payment endpoint. It accepts a pain.001.001.09 document, validates it against a local XSD, parses the generated model, and returns a compact summary and a reserialized business document. Its second operation parses the complete pacs.008 fixture to demonstrate that constructing or serializing a message is distinct from sending it.</p><pre>MxPain00100109 message = MxPain00100109.parse(xml);<br>var initiation = message.getCstmrCdtTrfInitn();<br>String customerMessageId = initiation.getGrpHdr().getMsgId();<br>String document = message.document();</pre><p>This is an excerpt from the companion’s parsing boundary, not a complete controller. XSD validation runs separately before it. The endpoint does not claim usage-guideline or business approval. Its response explicitly identifies those checks as not performed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zcW6ZiwDgDr1fFOtNK0VOw.png" /></figure><p><em>Figure 10. Parsing and serialization are local capabilities; connectivity and payment authorization are separate components.</em></p><p>For XML received from outside the process, disable external entities and external schema access. Load trusted schema resources explicitly. Apply payload size limits before parsing. Do not rely on a reassuring library class name as evidence that hostile XML cannot resolve external resources.</p><p>The focused tests check valid fixture parsing, rejection of an invalid amount by the XSD, and rejection of a document type declaration. These tests protect actual boundaries. A test that compares every generated setter with the same handwritten XML template would give much less confidence about the risks that matter.</p><p>The companion pins Spring Boot 3.5.5 and Prowide ISO 20022 SRU2025–10.3.6 to make the example reproducible. Those pins are not a recommendation to treat either release as the latest production baseline. Dependency support, security updates, and compatibility with the target message release remain deployment decisions. The application binds to localhost and accepts UTF-8 XML with a small payload limit; it has no customer authentication, database, or production validation catalogue.</p><h3>Dispatch creates uncertainty that retries must respect</h3><p>The inspection service has no SWIFT gateway. Its small mock gateway demonstrates three outcomes: accepted locally, rejected locally, and outcome unknown. The last case exists because a network timeout can happen after a remote system has accepted a request. It must not be represented as a definite failure that automatically permits a new economic payment.</p><p>In a production design, a transactional outbox can record the authorized outgoing intent alongside the payment’s durable state. A dispatcher sends that intent and records evidence. The outbox alone does not guarantee exactly-once execution across a remote financial network. Duplicate controls, correlation, reconciliation, and the remote service’s supported recovery procedure still matter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p_G2365H8FcfNSU95DX3Sw.png" /></figure><p><em>Figure 11. Unknown delivery requires investigation or a supported recovery procedure, not an unconditional new payment.</em></p><p>Use an idempotency key scoped to the submitting party and operation. Store a canonical request fingerprint with it. A retry using the same key and same request can retrieve the existing result; the same key with a different amount must produce a conflict. Do not make a customer’s free-form remittance reference the sole uniqueness constraint.</p><p>Retain enough audit evidence to reconstruct message creation, approval, dispatch attempts, acknowledgments, and subsequent business reports. Protect raw messages because names, accounts, addresses, and remittance data can be sensitive. Logging every payload in an application console is neither a reconciliation strategy nor a safe default.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S1Gtd-qnT1AA1G6KRZw7qw.png" /></figure><p><em>Figure 12. A current status is a projection of evidence; the underlying events remain available for audit and reconciliation.</em></p><p>The useful output of this architecture is more than XML. It is a traceable relationship between an authorized customer request, a bank’s route and funding decisions, a versioned outgoing instruction, and the evidence received afterward. The next article follows that evidence through pain.002 and pacs.002, where the word “accepted” becomes useful only when its scope is understood.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bbf2e77f979" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding MX Messages, Part 1: How pain.001 Expresses a Payment Instruction]]></title>
            <link>https://medium.com/@youssefelmessbahi/understanding-mx-messages-part-1-how-pain-001-expresses-a-payment-instruction-58e10ae58248?source=rss-573653523742------2</link>
            <guid isPermaLink="false">https://medium.com/p/58e10ae58248</guid>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[iso20022]]></category>
            <category><![CDATA[payments]]></category>
            <category><![CDATA[pain001]]></category>
            <category><![CDATA[e-banking]]></category>
            <dc:creator><![CDATA[YOUSSEF EL MESSBAHI]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 15:11:01 GMT</pubDate>
            <atom:updated>2026-11-02T20:08:38.921Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BLPhr-fnpuh1T1CN3Oex7Q.png" /></figure><p>Atlas Components has approved three supplier invoices. Its treasury application produces a file, sends it to its bank, and records the upload as successful. Has Atlas paid its suppliers? The application cannot answer that from the upload alone. It has evidence that an instruction was submitted. Execution, interbank settlement, beneficiary credit, and account reporting remain separate events.</p><p>That distinction is the starting point for understanding MX messages. A message represents a particular business action between particular participants. Reading XML becomes much easier once you know what that action is, which account it concerns, and which facts the sender is entitled to report.</p><p>Throughout this series, Atlas Components, a Casablanca manufacturer, uses CIH Bank as its illustrative sending bank. Banque Populaire, Bank of Africa, and Attijariwafa bank appear in fictional scenarios. Iberia Machines and European Banks E and F are fictional. These examples do not describe the real banks’ implementations, product availability, or correspondent relationships. Account identifiers are teaching labels, never payment destinations.</p><h3>1. Start with the business contract, then read the XML</h3><p>ISO 20022 provides a modelling approach, a business dictionary, and message definitions. In this series, MX refers to the XML financial messages used in the Swift ecosystem. ISO 20022 is broader than Swift, and the same message family can be used in different payment communities with different implementation rules.</p><p>The identifier pain.001.001.09 tells us the business area, message functionality, variant, and version. Here, pain is Payments Initiation; 001 identifies Customer Credit Transfer Initiation; the next 001 is the variant; 09 is the version. The namespace fixes the vocabulary that an XML document uses. Changing that namespace does not upgrade the document’s structure automatically.</p><p>Our teaching fixtures use pain.001.001.09 and base ISO schemas. They are not advertised as ready-to-send CBPR+, SEPA, or Moroccan domestic messages. A production interface must select the version and usage guideline agreed with its receiving institution. The newest ISO version is not necessarily the version that a particular service accepts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nimMxfMstA4XscdDZmAE2Q.png" /></figure><p><em>Figure 2. A business definition, XML schema, usage guideline, and transport service answer different questions.</em></p><p>FIN is associated with Swift MT messaging. FINplus supports relevant ISO 20022 exchanges, including interbank payment-initiation relay. CBPR+ defines usage rules and market practice for its exchanges; it does not perform settlement. Nor should every MT message be described as ISO 15022: that standard has a particular historical scope, especially in securities messaging.</p><p>A proprietary JSON API can capture the same business facts as pain.001 without being a pain.001 XML message. HTTP is a transport protocol, JSON is a representation, and the payment contract supplies the meaning. Keep these dimensions separate in specifications and operational logs.</p><h3>2. What pain.001 asks the bank to do</h3><p>CustomerCreditTransferInitiation is an instruction to initiate one or more credit transfers. The initiating party sends it to a receiving agent, directly or through an agreed relay arrangement. It identifies the funding side, intended beneficiaries, amounts, execution requests, and information needed to process the payments.</p><p>Its existence does not establish that the bank accepted the instruction. Acceptance does not establish that the account was debited. A debit does not establish that the beneficiary has been credited. These statements refer to different stages and sometimes to different institutions’ books.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jMqrzI7bq3JX_asn9aizUw.png" /></figure><p><em>Figure 3. The initiation, interbank instruction, and customer report occupy different parts of the journey.</em></p><p>Atlas’s domestic example contains MAD 48,000 for Casablanca Metals at Banque Populaire, MAD 32,000 for Rif Logistics at Bank of Africa, and MAD 20,000 for Atlas Maintenance at Banque Populaire. The total principal is MAD 100,000. We assume an illustrative corporate channel accepts this batch. We make no assertion about the bank’s actual outgoing domestic message format or clearing interface.</p><p>A separate international example requests EUR 25,000 for Iberia Machines at European Bank E. Keeping this payment separate makes it easier to distinguish customer-side grouping from the interbank execution that follows. A bank may receive a bulk customer instruction and create individual interbank instructions under the chosen usage profile.</p><h3>3. The initiating party is not necessarily the debtor</h3><p>In the straightforward case, Atlas initiates and its account funds the payment. InitgPty and Dbtr therefore describe the same organisation in different roles. Duplication of the name is not redundancy in the model: it records that two responsibilities happen to coincide.</p><p>Now suppose Atlas authorises an external treasury provider to submit instructions. The provider is the initiating party, while Atlas remains the debtor and its account remains the funding account. Permission comes from the service arrangement, mandates, authentication, and bank controls. Writing a company name into InitgPty does not grant debit authority.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FHfwYb6eCnYvvgQl5q7Sbg.png" /></figure><p><em>Figure 4. Delegating initiation changes the initiating party without necessarily changing the funding account.</em></p><p>A forwarding agent is a financial institution that receives and forwards an initiation in the relevant arrangement. In our alternative relay route, Atlas submits through Attijariwafa bank and CIH services the account to be debited. The institution that transports the instruction toward CIH is not thereby the institution funding the supplier payment. Relay agreements can also impose authentication and verification responsibilities; forwarding is not an absence of responsibility.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hw8eoKGHjIa2PHAOPVBeTg.png" /></figure><p><em>Figure 5. Alternative initiation route: the forwarding agent relays the request to the account-servicing debtor agent.</em></p><p>In a payment-on-behalf-of alternative, Atlas Holdings uses its own account to discharge an obligation of Atlas Components. Holdings is the debtor in the instruction; Atlas Components is the ultimate debtor. An ultimate creditor can similarly identify the party ultimately owed money when it differs from the immediate creditor. These roles should describe a real business arrangement, not be filled merely because the schema offers them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q8tF9ID2VuWuMk_kxSs_iA.png" /></figure><p><em>Figure 6. Alternative POBO arrangement: the account owner and the underlying obligor are distinct.</em></p><h3>4. Three levels explain most of the structure</h3><p>Inside Document, CstmrCdtTrfInitn contains one Group Header and one or more Payment Information blocks. Each payment-information block contains one or more Credit Transfer Transaction Information blocks. The hierarchy is message, funding/execution group, then individual instruction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MJ6_iH6GF6uAtcaU7H8MeA.png" /></figure><p><em>Figure 7. Repetition creates bulk payments; the individual transfer remains a distinct instruction.</em></p><p>GrpHdr identifies the message and its creator. NbOfTxs counts the transactions in the message. CtrlSum, when used, is a numerical control total of individual amounts irrespective of currencies; it is not an FX-converted economic valuation. A mixed-currency control sum can be useful for detecting transmission differences while remaining meaningless as a treasury balance. Our MAD-only batch avoids that ambiguity.</p><p>PmtInf groups the debit-side context: debtor, debtor account, debtor agent, payment method, and requested execution date. Different debit accounts or execution dates require appropriate separate groups. Creating a group does not inherently establish one account posting or an all-or-nothing processing promise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TbdEzL-Wq2a8RhB3z7b54g.png" /></figure><p><em>Figure 8. Three transaction amounts reconcile to the message control sum of MAD 100,000.</em></p><p>BtchBookg requests batch or individual booking. It concerns how entries are booked, subject to the servicing bank’s agreement. It does not mean that all beneficiaries are credited simultaneously, that an interbank system nets the transfers, or that every transaction must succeed together. Those are separate processing and settlement questions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JT6G1Wgpf07Dx6hzhvVzPw.png" /></figure><p><em>Figure 9. Alternative posting presentations for the same successful batch principal; fees are excluded.</em></p><p>At transaction level, CdtTrfTxInf holds the payment’s own identification, amount, creditor, creditor account, and related information. Cardinality such as 0..1 or 1..n describes permitted occurrences. A nested field can be mandatory when its optional parent is used. An optional base-schema field can also become required by a usage guideline or bank contract.</p><h3>5. References have different scopes</h3><p>Atlas assigns MsgId ATLAS-MAD-20261019–01 to the batch message and PmtInfId ATLAS-SUPPLIERS-MAD to its payment group. The three transfers use EndToEndId values ATLAS-D01, ATLAS-D02, and ATLAS-D03. These references answer three different questions: which submission, which group, and which customer transaction?</p><p>InstrId identifies an instruction between an instructing and instructed party where used. EndToEndId identifies the transaction from the initiating party’s perspective and is intended to travel unchanged through the chain. UETR supplies a universally unique transaction reference in supported contexts. It is not interchangeable with an invoice number or a file identifier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0EU1hAKg3bVAdF21yTfGSg.png" /></figure><p><em>Figure 10. Correlation preserves relationships between identifiers instead of forcing one identifier to serve every purpose.</em></p><p>For the international example, the invoice is IM-2026–1042 and the EndToEndId is ATLAS-X01. Keeping those separate permits one invoice to have partial payments or several invoices to be settled by one payment. Remittance information explains the commercial allocation; a transport or message identifier should not carry that burden.</p><p>Store references together with customer, account, counterparty, and submission context. EndToEndId alone is not a universally safe database uniqueness constraint: profiles may allow NOTPROVIDED, customers may reuse values incorrectly, and distinct customers can generate the same text. Duplicate detection needs an explicit scope and retention policy. Correlation tells you what an event relates to; idempotency tells you whether an operation should execute again.</p><h3>6. Read the fields as operational questions</h3><p>CreDtTm belongs to the creation of this message. It is not the requested execution time, and it is not evidence of the time at which a bank received the document. Preserve channel receipt time separately. If an ERP regenerates a file after a failed upload, changing this timestamp does not by itself make its underlying payments new obligations.</p><p>Authstn can carry authorization information in supported arrangements. It should not be treated as a password or as a substitute for authenticated submission and account entitlement checks. A field that describes authorization is different from the controls that establish whether the request is authorized. This distinction matters especially when an application allows a treasury provider to initiate on behalf of several companies.</p><p>Versions also change the available fields. The pain.001.001.09 teaching schema does not contain every element found in newer descriptions of pain.001. An integration specification that combines fields from several versions can look convincing in a spreadsheet and still describe an impossible XML document. Start from the selected namespace and its message definition, then apply the agreed restrictions.</p><p>ReqdExctnDt asks when the debtor agent should execute the instruction. It should not be renamed “beneficiary value date” in an application. Interbank settlement date and creditor booking date answer different questions. A requested date can be affected by validation, calendars, service availability, and agreed handling of late instructions.</p><p>Dbtr and DbtrAcct identify the debtor and its account; DbtrAgt identifies the servicing institution. Cdtr, CdtrAcct, and CdtrAgt describe the beneficiary side. The use of an IBAN does not mean a BIC is literally embedded within it. Bank identification may be resolved through country-specific account structure and maintained reference data. Missing information can require repair rather than a speculative name lookup.</p><p>ChrgBr describes charge allocation: DEBT, CRED, SHAR, or SLEV according to the applicable contract and profile. SLEV means that the agreed service-level rules govern charges. It is not a universal synonym for every possible shared-charge arrangement. A separate charges account can be identified when supported, but that does not change the principal’s funding account.</p><p>RmtInf carries information for matching the transfer to commercial obligations. Unstructured remittance is text; structured remittance offers dedicated elements for references and documents. RltdRmtInf can point to remittance supplied separately. Regulatory reporting, tax, agent instructions, cheque information, and supplementary data solve more specialised requirements. Their presence is version-dependent, and extensions require a governed agreement and applicable approval rules. Free text is not a substitute for a defined processing contract.</p><h3>7. Payment Type Information describes requested treatment</h3><p>InstrPrty expresses processing priority. SvcLvl identifies an agreed service level or rules. LclInstrm identifies a community-specific instrument. CtgyPurp supplies a high-level processing category, such as supplier payments. Purp, outside this block, describes the underlying reason for the transaction. Remittance supplies the commercial detail needed to allocate it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mhoM8z8abNDzDyjKB_mpqQ.png" /></figure><p><em>Figure 11. Priority, service level, instrument, purpose, and remittance provide complementary information.</em></p><p>An instruction marked HIGH does not bypass sanctions checks, create liquidity, or guarantee beneficiary credit by a deadline. A service-level code is not proof of eligibility. The bank must still check currency, participants, product agreement, and reachability. Likewise, inserting SEPA into an instruction from a Moroccan account does not by itself make that transfer a SEPA credit transfer.</p><p>Payment Type Information can have group and transaction placements in the ISO model, but this is not a general configuration language where the lowest value always wins. The applicable message constraints and implementation guide determine permitted placement and coexistence. The examples here place common values at the group level and avoid conflicting transaction-level values.</p><p>External code lists evolve separately from XSD files. A schema can accept a string while the selected external code is invalid or inappropriate for the profile. Keep the code-set edition and usage guideline visible in validation configuration, rather than scattering plausible-looking strings through Java enums.</p><h3>8. Amounts and FX: identify what is fixed</h3><p>For the international payment, Atlas instructs EUR 25,000. InstdAmt records the instructed amount before deduction of charges. It does not guarantee that the beneficiary’s net account increase equals EUR 25,000 under every charge arrangement. Nor does it necessarily equal the debit to Atlas’s funding account.</p><p>In the main example Atlas uses an illustrative EUR account, so no debtor-side FX is needed. In the explicitly alternative funding example, its account is in MAD. At our hypothetical rate of 1 EUR = MAD 10.80, the principal costs MAD 270,000 before fees. This arithmetic is a teaching assumption, not a market quote or statement about exchange-control eligibility.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8RCfG3XZ6MMffIehqVCoIw.png" /></figure><p><em>Figure 12. Fixing the transfer principal and fixing its equivalent in account currency are alternative instructions.</em></p><p>EqvtAmt expresses an amount in the debtor-account currency together with the currency of transfer. Suppose Atlas instead fixes MAD 270,000 as the principal equivalent and specifies EUR as CcyOfTrf. At 10.80 MAD per EUR, the derived transfer principal is EUR 25,000. Additional charges may still affect the total account debit; “fixed equivalent amount” must not be sold to users as an unconditional all-in spending cap.</p><p>The amount structure is a choice: use the supported InstdAmt or EqvtAmt branch, not both. With UnitCcy EUR and XchgRate 10.80, one EUR buys 10.80 MAD. Converting EUR to MAD multiplies; converting MAD to EUR divides. A rate without its quotation direction is incomplete information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uk_qk8oNSzgUjGHHpNjwLg.png" /></figure><p><em>Figure 13. The same quotation supports multiplication in one direction and division in the other.</em></p><p>RateTp and CtrctId help describe the rate arrangement and related contract. They do not prove that a valid treasury deal exists. Check ownership, currency pair, available contract amount, dates, and actual contractual terms. If no rate is supplied, the bank’s agreed pricing process may determine one. Preserve the original instruction and separately record the applied rate, rounding method, principal debit, and fees. Use decimal arithmetic and explicit currency precision, never binary floating point for money.</p><h3>9. MT101 comparison requires meaning, not tag replacement</h3><p>MT101 is a Request for Transfer. Its sequence A carries general information, while sequence B repeats transaction details. pain.001 provides explicit payment-information grouping and richer structured data. MT101 is nevertheless a defined, machine-readable format with field and network rules; it is misleading to describe it as unstructured text that banks simply guess how to interpret.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mXfsy2Iqjsq_1y5b26n_sA.png" /></figure><p><em>Figure 14. Selected functional correspondences require structural and usage-context checks.</em></p><p>Field 20 is a useful comparison for message identification, field 30 for requested execution date, and field 21 for an individual transaction reference. That does not make field 21 universally equivalent to PmtInfId: one is transaction-scoped and the other identifies a payment-information group. Field 28D identifies a message’s position within a series; it does not count credit-transfer transactions.</p><p>Field 32B, party fields, and field 70 offer other functional correspondences for amount, participants, and remittance. Structured party data, reference preservation, instruction codes, FX context, and multiple debit-side groups can require more than a direct assignment. Conversely, richer MX data can lose meaning when compressed into MT fields. A translation specification should document losses, defaults, splits, and rejection rules rather than promise lossless conversion.</p><h3>10. Read an instruction, then validate its meaning</h3><p>The following is an excerpt from pain.001.001.09, showing the essential relationship between the group and its first transaction. It intentionally omits required surrounding elements and is not a complete message.</p><pre>&lt;PmtInf&gt;<br>  &lt;PmtInfId&gt;ATLAS-SUPPLIERS-MAD&lt;/PmtInfId&gt;<br>  &lt;PmtMtd&gt;TRF&lt;/PmtMtd&gt;<br>  &lt;BtchBookg&gt;true&lt;/BtchBookg&gt;<br>  &lt;NbOfTxs&gt;3&lt;/NbOfTxs&gt;<br>  &lt;CtrlSum&gt;100000.00&lt;/CtrlSum&gt;<br>  &lt;ReqdExctnDt&gt;&lt;Dt&gt;2026-10-19&lt;/Dt&gt;&lt;/ReqdExctnDt&gt;<br>  &lt;!-- Debtor, account and debtor agent omitted here --&gt;<br>  &lt;CdtTrfTxInf&gt;<br>    &lt;PmtId&gt;&lt;EndToEndId&gt;ATLAS-D01&lt;/EndToEndId&gt;&lt;/PmtId&gt;<br>    &lt;Amt&gt;&lt;InstdAmt Ccy=&quot;MAD&quot;&gt;48000.00&lt;/InstdAmt&gt;&lt;/Amt&gt;<br>    &lt;Cdtr&gt;&lt;Nm&gt;Casablanca Metals&lt;/Nm&gt;&lt;/Cdtr&gt;<br>    &lt;CdtrAcct&gt;&lt;Id&gt;&lt;Othr&gt;&lt;Id&gt;DEMO-CM-MAD&lt;/Id&gt;&lt;/Othr&gt;&lt;/Id&gt;&lt;/CdtrAcct&gt;<br>    &lt;RmtInf&gt;&lt;Ustrd&gt;Invoice CM-2026-301&lt;/Ustrd&gt;&lt;/RmtInf&gt;<br>  &lt;/CdtTrfTxInf&gt;<br>  &lt;!-- Two further transactions omitted --&gt;<br>&lt;/PmtInf&gt;</pre><p>Read the sequence as a contract. Atlas identifies a group of three transfers, requests batch booking, provides a requested date, and identifies the first beneficiary and principal. The bank must still authenticate the sender, verify authority over the account, validate the remaining data, and decide whether the instruction can proceed.</p><p>A robust intake process therefore separates XML parsing, XSD structure validation, message business constraints, community usage rules, and operational business checks. A parser accepting the XML proves very little about the account, the beneficiary, or the availability of funds. Even a perfectly validated instruction may later fail execution.</p><p>For example, a file can declare three transactions while actually containing two. Those are individually well-typed values, so structural validity alone should not be relied on to establish their consistency. Count the transaction elements at the correct scope and compare them with declared counts. Where a control sum is supplied, calculate it with exact decimal arithmetic using the amount choice actually present. Keep those consistency checks distinct from a decision that sufficient funds exist.</p><p>This separation also improves error handling. A malformed document might not contain enough trustworthy references for a normal transaction report. A valid message with one unacceptable beneficiary can support a precise transaction rejection if the service allows partial processing. A missing acknowledgement leaves uncertainty that must be resolved before retransmitting. Your software should retain the original submission, validation result, and correlation context so these situations remain distinguishable.</p><p>The next article follows the international instruction into the debtor bank. There, the bank must turn Atlas’s request into an executable interbank instruction, adding decisions and information that the customer’s pain.001 alone cannot supply.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58e10ae58248" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding SWIFT MT Messages: From Message Blocks to Payment Meaning]]></title>
            <link>https://medium.com/@youssefelmessbahi/understanding-swift-mt-messages-from-message-blocks-to-payment-meaning-23ddc65e27cb?source=rss-573653523742------2</link>
            <guid isPermaLink="false">https://medium.com/p/23ddc65e27cb</guid>
            <category><![CDATA[iso15022]]></category>
            <category><![CDATA[e-banking]]></category>
            <category><![CDATA[payments]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[fintech]]></category>
            <dc:creator><![CDATA[YOUSSEF EL MESSBAHI]]></dc:creator>
            <pubDate>Mon, 19 Oct 2026 21:05:41 GMT</pubDate>
            <atom:updated>2026-10-19T21:05:41.733Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. A payment instruction is not the payment itself</h3><p>Atlas Components, a manufacturer in Casablanca, owes Iberia Machines EUR 25,000 for invoice IM-2026–041. Its treasury application prepares an instruction for its bank. Somewhere downstream, an engineer sees an acknowledgment and updates the payment to “completed.” The supplier checks its account. There is no credit.</p><p>The mistake was not necessarily in transmission. It was in the meaning assigned to the evidence. A message can be received before it is accepted for execution. An instruction can be accepted before funds are posted. A particular interbank leg can settle before the beneficiary’s account is credited. Those are different events, produced by different systems.</p><p>An MT message is structured financial communication. Its message type defines the business purpose; its fields express the details; its headers identify the messaging context. It does not carry money inside its text. Payment execution requires institutions to act on instructions and make the relevant accounting entries under their arrangements.</p><p>In this article, Atlas uses CIH Bank as its illustrative account-servicing bank. Iberia Machines banks with fictional European Bank E. All businesses, account identifiers, technical addresses, routes, and processing assumptions are teaching examples; they do not describe the named real bank’s actual implementation or correspondent relationships. We assume Atlas has sufficient EUR funds, so the main example does not involve FX.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fnn4eSUBBWBElmcI-3F7dg.png" /></figure><p><em>Figure 02. Communication, bank processing, interbank accounting, and beneficiary credit require distinct evidence. The diagram is a simplified successful path, not a universal timing rule.</em></p><p>Start every investigation by asking: what does this particular artifact prove? A parsed message proves that software extracted a representation. A technical acknowledgment concerns messaging acceptance. An account entry records a posting on a particular ledger. None should silently stand in for all the others.</p><h3>2. MT, FIN, MX: separate the vocabulary</h3><p>MT means Message Type. Standards MT defines a family of messages used for different financial purposes. MT101 is a Request for Transfer; MT103 is a Single Customer Credit Transfer. The number identifies a specification, not a free-form label an application may assign to arbitrary text. These two messages concern customer payments, but they sit at different stages and have different senders, responsibilities, and field structures.</p><p>FIN is SWIFT’s messaging service traditionally used to exchange MT messages. FINplus is used for ISO 20022 exchanges in contexts including CBPR+. A transport service, a message definition, and a market usage guideline answer different questions: how is information exchanged, what does it mean, and which permitted features may this community use?</p><p>ISO 20022 supplies financial business models and message definitions; XML is the familiar syntax of its payment messages. CBPR+ specifies how selected ISO 20022 messages are used for cross-border payments and reporting. An XML document can fit its base schema yet violate a CBPR+ restriction. Equally, an MT can be structurally readable yet violate a message rule.</p><p>Do not call every MT “ISO 15022.” That standard concerns securities messaging and its data-field/message-design framework. MT101 and MT103 should be identified by their SWIFT Standards MT definitions, not indiscriminately placed under an ISO 15022 label.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ev7SVqlLFDrb-qGXrUTh2w.png" /></figure><p><em>Figure 03. Message definitions, syntax, transport services, and usage rules are related but are not interchangeable.</em></p><p>There is also a date boundary. The CBPR+ coexistence period for in-scope cross-border interbank payment instructions ended in November 2025. That did not remove every MT use case. Corporate MT101 initiation has a different migration context from interbank relay. Here, the MT103 is a historical-format teaching example, useful for understanding archives, integrations, and semantic translation; it is not a recommendation to originate new CBPR+ payments as MT103 in 2026. The examples use the SRU2025 field model for parsing, with historical MT semantics.</p><p>Learning MT helps explain data constraints that integrations still encounter. It is not a prerequisite for learning ISO 20022, and ISO 20022 is much broader than an XML rewrite of MT.</p><h3>3. Read the envelope before the instruction</h3><p>A typical FIN user-to-user message can contain five numbered blocks. Blocks 1 and 2 describe messaging context; Block 3 contains additional header information; Block 4 contains business fields; Block 5 carries trailer information. Presence and requirements depend on the message and service context. System messages and acknowledgments must not be forced into the same template as customer-payment messages.</p><p>Consider this <strong>input-header excerpt</strong>, using invented technical addresses:</p><pre>{1:F01CIBKMAXXAXXX0001000001}<br>{2:I103EUBKESMMXXXXN}<br>{3:{108:ATLASOUT000041}{121:123e4567-e89b-42d3-a456-426614174000}}</pre><p>The line breaks between blocks improve readability here. This is not a complete network-ready message, and the invented BIC-shaped identifiers are not directory-validated addresses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ve7Xl2wJmLAR-wXpzjqjg.png" /></figure><p><em>Figure 04. Each block answers a different operational question. This anatomy concerns a typical FIN business message, not every FIN service message.</em></p><p>In Block 1, F identifies the FIN application and 01 the user-to-user service. The logical-terminal address has 12 characters: an eight-character BIC component, a logical-terminal character, and a three-character branch component. It is not simply a BIC11. The four-digit session and six-digit sequence provide messaging context; they are not the customer’s invoice reference.</p><p>Direction matters. In an input message submitted to SWIFT, Block 1 identifies the sender’s logical terminal. In an output message delivered by SWIFT, it identifies the receiver’s logical terminal. “Input” and “output” are from the network’s perspective, not your application’s business perspective.</p><p>The input Block 2 starts with I, followed by 103, a destination address, and N for normal priority in this example. Its output counterpart starts with O and has a different layout, including the Message Input Reference and timing information. Do not apply input offsets to an output header. Optional delivery-related components also make “both headers always have one fixed length” an unsafe simplification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oAv6qB5-AOpsYGNUeQ3tug.png" /></figure><p><em>Figure 05. SWIFT receives an input message and delivers an output message. Header interpretation must follow that perspective.</em></p><p>Block 3 uses nested elements. 108 is the Message User Reference, useful for application-to-interface correlation. 121 carries the UETR in applicable payment messages. The UETR follows the payment chain; it does not replace every local reference. A new institution may allocate its own sender reference while preserving the payment’s UETR. Do not assume MT101 has the same UETR requirements as MT103.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IgJGci-ry1IpvwnSnIs2mQ.png" /></figure><p><em>Figure 06. Preserve relationships between identifiers instead of forcing network, instruction, and invoice references into one database column.</em></p><p>Block 5 can carry integrity-related information and indicators such as possible duplicates. Treat those according to the interface and service specification. A displayed checksum is not a substitute for authenticating a channel or validating a local file’s provenance. Likewise, absence of a possible-duplicate indicator does not establish that your application has never processed the instruction.</p><p>The envelope helps answer who transmitted what to whom. It does not automatically reveal the entire correspondent route. Block 2 names the message recipient; business fields and banking arrangements determine the roles and execution path behind that exchange.</p><p>For troubleshooting, retain the original direction and envelope alongside the extracted business object. If a log records only the amount and customer names, an operations team may be unable to distinguish two submission attempts or correlate a network response with the correct outgoing message. Conversely, a session/sequence pair without the relevant sender and session context is not a universal business key. The application needs both perspectives, linked explicitly.</p><h3>4. Read Block 4 as a grammar</h3><p>Block 4 contains tagged fields. A field such as :70: introduces remittance information in the payment messages discussed here. Its value may occupy several lines. A newline alone does not mean “new field”: the parser must recognize the next field boundary. The text block closes with -} in the ordinary FIN business-message representation.</p><pre>:70:INV IM-2026-041<br>MACHINE PARTS<br>:71A:SHA</pre><p>Both the invoice line and MACHINE PARTS belong to field 70. Splitting this text on newlines and treating each line as a separate field loses information. Splitting on every colon is also unsafe: delimiters must be interpreted as grammar, not as arbitrary string separators.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b-iCyvgrGN7rvd5CqNnt0A.png" /></figure><p><em>Figure 07. A continuation line remains inside the current field; the next recognized tag starts another field.</em></p><p>The specification describes allowed content through compact notation. n allows digits; a allows uppercase letters; c allows uppercase letters and digits. x is a defined character set with letters, digits, and permitted punctuation, including lowercase letters. It does not mean arbitrary Unicode. An accented company name cannot simply be pasted into a restricted field without considering permitted characters and an agreed transliteration policy.</p><p>The number before the symbol gives a maximum length unless followed by !. Thus 6n permits up to six digits, while 6!n requires exactly six. The exclamation mark does not make the field mandatory; it fixes the component length if the field or component is used. Field presence is a separate rule.</p><p>4*35x allows up to four lines, each with up to 35 characters. It is not a pool of 140 freely distributable characters. Five twenty-character lines fail that shape even though their combined length is only 100. A single 50-character line also exceeds its limit. Production formatting must preserve meaning while respecting both constraints; silent truncation can remove a street number or invoice identifier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n48wjYxQYD3ez_0nbT_YZg.png" /></figure><p><em>Figure 08. Length, character class, and line repetition are independent constraints.</em></p><p>For amounts, d uses a decimal comma, which counts toward the length. The comma is required; thousands separators are not permitted. Under a 6d shape, 1234,5 fits six characters; 12345,6 does not. 1234.5 uses the wrong separator. The format alone is still insufficient: currency precision and applicable field rules further constrain valid amounts.</p><p>MT103 field 32A combines three components:</p><pre>Format: 6!n3!a15d<br>Excerpt: :32A:261019EUR25000,00</pre><p>Read six digits as the date, three letters as currency, and the remaining decimal component as amount: 19 October 2026, EUR, 25,000.00. Exact component lengths make that concatenation interpretable without separators. Six numeric characters alone do not prove a real calendar date: 261332 has the right character count but no valid month/day meaning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SXQEjEoxlQQbRbj3cjRCWA.png" /></figure><p><em>Figure 09. One MT field contains a value date, a currency, and an interbank settled amount; its name does not prove settlement has occurred.</em></p><p>MT101 uses 32B for currency/transaction amount. Do not feed it into a 32A parser and assume the first six characters are a date. The message specification and field option define the grammar together.</p><p>Square brackets describe optional components; they are not literal characters to transmit. An optional account component such as [/34x] means the slash belongs with the account when that component is present. Optionality does not allow you to drop required punctuation while retaining its value.</p><h3>5. Letter options, slashes, and business context</h3><p>A field option selects a representation permitted by that message definition. An agent field with option A commonly carries an identifier code, whereas option D commonly carries name and address. That is a useful pattern, not a universal rule that every number supports every option. MT103 ordering customer 50K and MT101 ordering customer 50H are not interchangeable merely because both can contain account and name/address information.</p><p>For an option-A agent representation, a slash-prefixed party-identifier line and a BIC line have distinct roles. The following are <strong>field excerpts</strong> using fictional values:</p><pre>:57A:/EURACCOUNT01<br>EUBKESMMXXX</pre><p>The first line is a party identifier in that field’s format; the second is the identifier code. If you write only /EUBKESMMXXX, the slash changes the structural interpretation. Its visual resemblance to a BIC does not supply the missing mandatory identifier-code line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tR2EQdvx1QbxwHh1Ws-rqA.png" /></figure><p><em>Figure 10. Data that looks like a BIC is not necessarily located in the BIC component.</em></p><p>Double slashes are equally contextual. In certain agent fields they introduce national clearing-system identification. In field 72 they can introduce continuation information after a coded instruction. There is no safe global algorithm that gives every // the same business meaning. Parse the field first, then its substructure.</p><p>MT101 provides an especially useful warning against interpreting tags in isolation. Field 50 with options C or L represents the instructing party, while options F, G, or H represent the ordering customer. A treasury entity authorized to initiate a request may differ from the account owner whose funds are debited. Collapsing these into one “customer” object can damage authorization checks and downstream party mapping.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gIjXacjyhFeNHzh0NIew3g.png" /></figure><p><em>Figure 11. In MT101, the permitted option distinguishes instructing-party and ordering-customer representations.</em></p><h3>6. Follow Atlas Components’ MT101</h3><p>Atlas asks its account-servicing bank to execute the supplier payment on 19 October 2026. The bank must recognize the customer arrangement, validate the request, check authorization and funds, perform its controls, and select execution details. Receipt of MT101 is the start of that responsibility, not proof that those checks succeeded.</p><p>MT101 has a non-repeating Sequence A and repeating Sequence B. Sequence A contains shared information; each Sequence B describes a transaction. “Sequence A” and “Sequence B” are specification groupings, not text labels inserted into the message. The message does not use XML-style nesting to make those groupings obvious.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dzjKoRJh0ZGvXoc52zVh3A.png" /></figure><p><em>Figure 12. The two-transaction version is an alternative to the single-payment example, not an additional submission of it.</em></p><p>This is the <strong>complete Block 4 for the simplified single-transaction teaching case</strong>, not a complete FIN envelope or certified payment instruction:</p><pre>{4:<br>:20:ATLAS26101901<br>:28D:1/1<br>:50H:/ATLAS-EUR-001<br>ATLAS COMPONENTS<br>12 RUE DES ATELIERS<br>CASABLANCA MA<br>:30:261019<br>:21:ATLASINV260041<br>:32B:EUR25000,00<br>:57A:EUBKESMMXXX<br>:59:/IBERIA-EUR-001<br>IBERIA MACHINES<br>8 CALLE INDUSTRIA<br>MADRID ES<br>:70:INV IM-2026-041<br>MACHINE PARTS<br>:71A:SHA<br>-}</pre><p>20 identifies this message as ATLAS26101901. 28D:1/1 says it is message one of a one-message series; it does not say there is one transaction. Chained-message numbering is different from the number of transactions and different again from a file container’s record count. Do not make a dollar-sign file separator part of your universal MT grammar: packaging conventions belong to the interface contract.</p><p>50H supplies Atlas’s account and ordering-customer details. Here it appears in Sequence A because it applies to the transaction set. 30 is the requested execution date. It is neither a guaranteed completion date nor automatically the settlement date of a later interbank instruction. A sanctions hold, insufficient funds, or an execution cut-off can affect actual processing.</p><p>The first 21 starts Sequence B. ATLASINV260041 is the transaction reference. 32B instructs EUR 25,000.00. 57A identifies European Bank E using the fictional code EUBKESMMXXX. 59 identifies Iberia Machines and its account. 70 carries the invoice information intended to help the supplier reconcile the credit. 71A:SHA allocates charges on a shared basis; it does not disclose actual fee amounts or guarantee that the beneficiary receives exactly EUR 25,000.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pMSStlFqfKdcrsujZF1dnA.png" /></figure><p><em>Figure 13. Read the MT101 as a request with shared execution context and transaction-specific instructions.</em></p><p>Some information is implicit in our scenario. The receiver is the bank servicing Atlas’s account, so we have not added an explicit 52a account-servicing institution. Atlas initiates for itself, so there is no separate instructing party. These omissions are scenario decisions, not permission to omit required information in every customer or relay arrangement.</p><p>To create the two-transaction alternative, keep Sequence A and append another Sequence B with reference ATLASINV260042, EUR 7,500.00, and invoice IM-2026–042. Keep 28D:1/1: there is still one message. Each transaction must retain its own beneficiary, remittance, and charge instructions. The total is EUR 32,500, but that alone does not establish a single aggregate ledger debit.</p><p>Fields available at both levels require their actual presence rules to be respected. Do not implement “transaction value overrides header value” as a universal inheritance rule. Similarly, 21R is not a generic interchangeable identifier: its customer-reference and debit-grouping semantics require attention to the applicable rules and agreement. We omit it rather than imply batching behavior that our example has not defined.</p><p>Other optional fields become useful when the business case needs them: 21F can identify an FX deal; 23E can carry permitted processing instructions; 56a can identify an intermediary; 25A can specify a charges account. An FX deal reference points to an agreement the bank must resolve. It is not sufficient evidence, by itself, that a quoted rate remains available or applies to this transaction.</p><h3>7. MT103: the bank’s customer-credit-transfer instruction</h3><p>MT103 concerns a single customer credit transfer between financial institutions. The word “customer” describes the underlying payment; it does not mean the corporate necessarily sends the MT103. After accepting Atlas’s request, its bank can create an interbank instruction under the relevant payment arrangement. In our historical-format example, that instruction is represented as MT103.</p><p>The MT101 and MT103 are therefore related business events, not two file formats for an identical action. The bank adds execution context, assigns an outgoing reference, determines routing and settlement information, and applies charges as appropriate. A translator cannot replace those processing decisions by renaming tags.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P2-BMXSYgBS_UYz1CBtMcg.png" /></figure><p><em>Figure 14. MT101 requests execution; the historical MT103 represents an interbank customer-credit-transfer instruction resulting from processing.</em></p><p>For the baseline, assume direct messaging to European Bank E, an agreed EUR settlement arrangement, no FX, and no charges deducted or added to the principal in this illustrative instruction. Any separately booked customer fee is outside this example. The chosen interbank value date happens to equal the requested execution date; that equality is an assumption, not a mapping rule.</p><p>The following <strong>complete simplified Block 4</strong> uses the ordinary MT103 field model, not the MT103 STP variant. Its date is aligned with the recurring scenario for comparison; the MT103 representation remains historical/legacy instructional material, not a live 2026 CBPR+ submission:</p><pre>{4:<br>:20:CIBK261019000041<br>:23B:CRED<br>:32A:261019EUR25000,00<br>:33B:EUR25000,00<br>:50K:/ATLAS-EUR-001<br>ATLAS COMPONENTS<br>12 RUE DES ATELIERS<br>CASABLANCA MA<br>:59:/IBERIA-EUR-001<br>IBERIA MACHINES<br>8 CALLE INDUSTRIA<br>MADRID ES<br>:70:INV IM-2026-041<br>MACHINE PARTS<br>:71A:SHA<br>-}</pre><p>20 is now CIBK261019000041, allocated to the outgoing instruction. Persist its link to the MT101 message and transaction references. The MT103’s UETR belongs in the applicable user header, not inside field 20; the earlier header excerpt supplies an illustrative value.</p><p>23B:CRED identifies the bank operation as a credit transfer. 32A provides value date, currency, and interbank settled amount for the instruction. Despite the label “settled amount,” merely seeing this field is not evidence that an accounting entry has occurred. 33B carries currency/instructed amount. They are equal here because we assumed no FX and no principal adjustment for charges.</p><p>50K carries the ordering customer and account; 59 carries the beneficiary and account. Because the MT103 receiver is European Bank E in the direct example, we have not repeated it in 57a. 70 preserves the invoice information. 71A preserves the shared charge allocation for this example. Those fields support execution and reconciliation; none individually confirms the supplier’s available balance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B572OoaVoDGCk5iyBxWG_g.png" /></figure><p><em>Figure 15. The MT103 adds interbank execution information while retaining the underlying customer payment’s meaning.</em></p><h3>Which bank does each agent field describe?</h3><p>The header answers “who receives this message?” Optional business fields can identify other institutions. In a routed variation, CIH’s illustrative sending system addresses the MT103 to Bank F, while 57A identifies European Bank E as the account-with institution. Bank F receives the instruction; Bank E services the beneficiary. They must not be merged into a single receiver-bank property.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ITTjFA2hT5AJyvprO7lWjg.png" /></figure><p><em>Figure 16. Alternative historical serial route: Bank F is the immediate receiver, while Bank E is the beneficiary’s bank. This replaces the direct route.</em></p><p>Field 52a identifies the ordering institution when needed, distinct from the message sender. Field 53a describes the sender’s correspondent; 54a the receiver’s correspondent. These concern reimbursement arrangements and must not be treated as arbitrary extra intermediary slots. Field 56a identifies an intermediary institution; 57a identifies the account-with institution. Which fields are present depends on the route and the rules. Filling every agent field “for completeness” can assert a banking relationship that does not exist.</p><p>Field 72 carries sender-to-receiver information with prescribed usage and coding conventions. It is not an overflow bucket for truncated addresses or a second remittance field. An integration that puts beneficiary-facing invoice information there may prevent the supplier from receiving it in the expected form, or trigger manual handling.</p><h3>Amounts, charges, and two different paths</h3><p>OUR, SHA, and BEN in 71A allocate responsibility for charges to the ordering customer, shared parties, or beneficiary respectively. They are instructions about charge bearing, not a complete fee ledger. Field 71F records sender’s charges in the relevant sense of the MT103, including applicable prior deductions; 71G records receiver’s charges in the applicable prepaid-charge arrangement. Their presence and repetition are constrained by rules, including the charge code.</p><p>As a separate arithmetic variation, assume EUR 25,000 instructed, EUR 10 deducted in sender’s charges, no FX, and no prepaid receiver’s charges. The interbank amount becomes EUR 24,990. This illustrates why 33B and 32A can differ; it does not promise the final beneficiary credit or define a general-purpose FX formula. Do not subtract a charge a second time because it appears in 71F after it has already been reflected in 32A.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B9eeb9roGAA8XgFwfwqQ6g.png" /></figure><p><em>Figure 17. Baseline principal postings are shown separately from an alternative EUR 10 deduction. Each view has explicit assumptions; neither is a live-bank accounting model.</em></p><p>Serial and cover arrangements separate instruction and funding differently. In a historical serial route, the customer-credit-transfer instruction progresses through intermediary banks toward the beneficiary’s bank, with the relevant account arrangements supporting each leg. In a cover arrangement, the MT103 is sent toward the beneficiary’s bank while a separate MT202 COV funding instruction follows the reimbursement chain. The cover is funding for the same customer payment, not a second supplier payment. Receipt of the customer instruction does not prove that its cover has settled. Detailed MT202 COV fields require their own treatment.</p><p>At the end of either route, operational evidence still matters. A FIN acknowledgment is not a beneficiary-credit confirmation. Settlement of one correspondent leg is not proof that every subsequent leg or customer posting is complete.</p><p>The accounting perspective explains why. A customer deposit is generally a liability on its bank’s books: the bank owes that balance to the customer. In the simplified principal posting shown above, debiting that liability reduces what the bank owes Atlas. Crediting the bank’s nostro asset reduces its claim on the correspondent. Both entries decrease a balance, even though one is a debit and the other a credit. “Debit means money went out” is a customer-facing shortcut, not a complete accounting rule.</p><p>The beneficiary bank has its own books and its own evidence. Its customer-credit entry cannot be inferred solely from the sending bank’s debit entry. Real implementations may use clearing, suspense, and internal settlement accounts between these events. Our ledger view deliberately collapses those intermediate postings to explain the principal relationship; it does not prescribe a bank’s chart of accounts. A statement or confirmation can later report an event, but reporting that event and causing it are different responsibilities.</p><h3>8. Parsing is the first gate, not the last</h3><p>A parser builds a representation. Field checks assess lengths, characters, component structure, and values. Message-level validation assesses order, allowed occurrences, and dependencies. Usage validation applies the particular community’s restrictions. Business validation then asks whether this customer may instruct this debit, whether the account and currency are supported, and whether the bank can execute the request.</p><p>Prowide Core provides Java models, parsing, and serialization for MT. Prowide ISO 20022 is a separate library for MX models. Neither an MT object nor an MX object gives an application SWIFT connectivity or settlement capability. Comprehensive standards/usage validation is separate from simply calling a parsing method.</p><p>The accompanying Java example targets Java 21 and pins com.prowidesoftware:pw-swift-core:SRU2025-9.6.1. Its central operation preserves transaction boundaries:</p><pre>MT101 message = MT101.parse(fin);<br>for (MT101.SequenceB transaction : message.getSequenceBList()) {<br>    String reference = transaction.getTagValue(&quot;21&quot;);<br>    String currencyAmount = transaction.getTagValue(&quot;32B&quot;);<br>    // Parse and check this transaction&#39;s amount, not a global field list.<br>    Payment instruction = readPayment(reference, currencyAmount);<br>    payments.add(instruction);<br>}</pre><p>The full class in the kit checks that it received MT101, rejects missing or duplicate selected fields, converts the decimal comma to a BigDecimal representation, and checks currency fraction digits for its supported scope. These are focused extraction checks, not a replacement for the MT101 validation specification. The accompanying tests verify that the EUR 25,000 and EUR 7,500 instructions stay associated with the correct references, and that a decimal-point amount is rejected.</p><p>Collecting all 21 values and all 32B values independently and zipping them by index is fragile. A malformed or optional occurrence can shift the correspondence. Sequence-aware extraction keeps related fields together and lets you report which transaction failed. Serialization through the model produces MT text; it does not certify that the output satisfies every network or bilateral rule.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*McMnTshWCWld5Im8vIq5bQ.png" /></figure><p><em>Figure 18. Parsing, validation, submission, and financial completion are separate boundaries. A timeout can leave submission outcome unknown.</em></p><p>In a Spring Boot service, keep extraction separate from the component that accepts a business instruction and from the gateway adapter that submits it. Persist an accepted instruction and its outgoing work atomically where possible, for example through a transactional outbox. A database transaction cannot automatically roll back a message already accepted by an external network.</p><p>If submission times out, the result may be unknown. Blindly generating another outgoing reference and resending can create a second payment. Resolve the original attempt using gateway evidence and correlation before deciding on retransmission. Duplicate detection should consider authenticated sender/customer context, references, retained instruction content, and the agreed reference-reuse policy; amount and beneficiary alone are not a safe identity.</p><p>Keep an auditable chain from original message to normalized instruction, validation results, execution attempt, external references, and reconciled postings. Restrict access to raw messages, which contain account and personal data. Operational logs should expose enough correlation to investigate without printing every address and account. Reconciliation then compares expected instructions with actual execution and accounting evidence, rather than trusting a single status string.</p><h3>9. Translate meaning before translating syntax</h3><p>MT101 and pain.001 share customer-initiation concepts, but their grouping and representation differ. The ordering customer relates to debtor information; its account belongs in a separate account component. Remittance information has its own location. A requested execution date remains an execution request, not a settlement fact. These are semantic correspondences, not a universal transformation specification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nm-v9TCsap3-rylhfPO6eA.png" /></figure><p><em>Figure 19. MT-to-ISO work requires role, grouping, and information-quality decisions. The connections are conceptual, not a version-specific mapping contract.</em></p><p>One MT101 with several Sequence B transactions does not justify copying every value into one pain.001 payment-information group. Different debtor accounts, charges accounts, dates, or usage restrictions may require grouping or splitting decisions. Message identifiers, payment-information identifiers, instruction identifiers, end-to-end references, and UETRs also have different scopes. A familiar reference string is not automatically correct in every identifier field.</p><p>Likewise, MT103-to-pacs.008 work must preserve the difference between instructed and interbank amounts, message sender and debtor agent, and instruction receipt and settlement. A structured XML address cannot reliably be manufactured from an ambiguous free-text line without additional information. The reverse direction can lose detail when rich ISO data exceeds MT capacity. Translation needs explicit enrichment, truncation, rejection, and audit policies.</p><p>XSD validation checks XML structure and schema constraints. It does not establish CBPR+ compliance, business authorization, or settlement. Naming elements more clearly improves representation; it does not make incorrect data correct.</p><p>When the next MT arrives in a production incident, read it in layers. Establish its type and exchange context. Interpret the envelope in the right direction. Locate its business sequences. Decode fields according to their actual options. Link its references to the underlying instruction and account evidence. Then decide what has happened — and what you still need to prove.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23ddc65e27cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Bank Payments Really Work: From Moroccan Transfers to Correspondent Banking]]></title>
            <link>https://medium.com/@youssefelmessbahi/how-bank-payments-really-work-from-moroccan-transfers-to-correspondent-banking-6bce7b44eee0?source=rss-573653523742------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bce7b44eee0</guid>
            <category><![CDATA[banking]]></category>
            <category><![CDATA[iso20022]]></category>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[payments]]></category>
            <dc:creator><![CDATA[YOUSSEF EL MESSBAHI]]></dc:creator>
            <pubDate>Sun, 18 Oct 2026 15:04:15 GMT</pubDate>
            <atom:updated>2026-10-18T15:04:15.182Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Clearing, settlement, Nostro and Vostro accounts, and the role of SWIFT — explained through one company’s payments.</strong></p><p>Atlas Components, a manufacturer in Casablanca, has paid a supplier. Its online banking screen shows a debit. The finance manager sends the supplier a confirmation, but the supplier replies: “Nothing has arrived.”</p><p>Is the payment missing? Not necessarily. The debit proves that something happened at the sending bank. It does not, by itself, prove that every interbank obligation has settled or that the receiving bank has credited the beneficiary.</p><p>A payment connects instructions, account balances, institutional relationships, and evidence. Understanding those connections is the foundation for understanding <strong>SWIFT </strong>and payment standards. Before looking at message fields, we need to know what the messages are trying to accomplish.</p><p>We will follow Atlas Components through three environments: inside its own bank, across the Moroccan banking system, and into an international supplier payment. At each stage, ask four questions: Who owns the account? Who maintains it? Which balance changes? What confirms the change?</p><p>All businesses, payments, balances, and correspondent arrangements in this article are fictional. CIH Bank, Attijariwafa bank, Bank of Africa, and Banque Populaire are illustrative participants. The examples do not describe their actual internal systems, products, or bilateral relationships. Amounts are teaching examples, not scheme thresholds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CNVGY7VNH9gUR2qNI-AZjw.png" /></figure><p>The same company encounters different account and settlement arrangements as its payments move beyond one bank.</p><p><strong>1. Start inside one bank</strong></p><p>Atlas Components holds MAD 100,000 at CIH Bank. A maintenance company also banks at CIH and holds MAD 12,000. Atlas pays that company MAD 8,000.</p><p>After successful posting, Atlas has MAD 92,000 and the maintenance company has MAD 20,000. The combined balance remains MAD 112,000, ignoring fees. CIH has changed how much it owes each customer; this transfer does not require a payment to another bank.</p><p>A customer deposit is a claim on the bank. On the bank’s balance sheet, it is a liability: an amount the bank owes the account holder. Reducing Atlas’s deposit reduces one liability. Increasing the supplier’s deposit increases another.</p><p>From CIH’s accounting perspective, the simplified entry is a debit of MAD 8,000 to Atlas’s deposit liability and a credit of MAD 8,000 to the supplier’s deposit liability. “Debit” and “credit” describe accounting entries; their effect depends on the type of account. A credit increases a deposit liability, while a credit decreases an asset account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4s1JTKcnv9-2t--KsSV_ow.png" /></figure><p>Within one bank, this transfer reduces one customer deposit liability and increases another.</p><p>The bank still needs to authenticate the instruction, check authority and available funds, apply relevant controls, and prevent duplicate execution. An internal transfer is operationally simpler, not control-free.</p><p>For an engineer, the essential property is consistency. The system must not leave a completed debit with no corresponding credit. The implementation might use a transactional ledger or a controlled posting workflow. Whatever the architecture, its business invariant remains the same: all required entries must be accounted for, including any temporary entries used during processing.</p><p><strong>2. Another bank means another obligation</strong></p><p>Now Atlas pays MAD 25,000 to a packaging supplier at Banque Populaire. CIH can reduce Atlas’s balance, but it cannot directly edit the supplier’s account in Banque Populaire’s ledger.</p><p>Two things are needed: the receiving bank must obtain the payment information, and the obligation between the participating banks must be discharged through an agreed settlement arrangement. The supplier’s bank then records the customer credit according to the applicable process.</p><p>Three terms help separate these responsibilities.</p><p><strong>Clearing </strong>covers exchanging and processing payment instructions before settlement. Depending on the system, this includes validation, sorting, matching, and calculation of obligations. Netting may be part of clearing, but clearing does not always involve netting.</p><p><strong>Settlement </strong>discharges an obligation through the relevant settlement asset and accounts. In a central-bank settlement system, the banks’ balances at the central bank change. In correspondent banking, a balance held with a commercial bank may be used instead.</p><p>Posting records entries in a ledger. Crediting a beneficiary’s deposit is a posting at the receiving bank. Settlement also involves ledger entries, but those entries concern the settlement accounts, not necessarily the customer’s account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jZ78ySHDItiFPJdHgA3D6w.png" /></figure><p>Customer deposits and central-bank settlement balances belong to different account holders and ledgers.</p><p>This distinction exposes two kinds of money in our domestic example. Atlas’s deposit at CIH and the supplier’s deposit at Banque Populaire are commercial-bank money. The banks’ settlement balances at Bank Al-Maghrib are central-bank money. Atlas does not have a settlement account at Bank Al-Maghrib simply because its transfer ultimately uses central-bank settlement.</p><p>Using central-bank money avoids exposure to a private settlement bank for that settlement asset. It does not remove operational failures, liquidity constraints, fraud, or every other risk in the payment process.</p><p><strong>3. A domestic MAD transfer: where SIMT and SRBM fit</strong></p><p>Morocco’s payment infrastructure includes the Système Interbancaire Marocain de Télécompensation (<strong>SIMT</strong>) and the Système des Règlements Bruts du Maroc (<strong>SRBM</strong>). For our conceptual standard-transfer route, SIMT supports the exchange and clearing of payment items, while the resulting net positions are settled through SRBM at Bank Al-Maghrib.</p><p><strong>SRBM </strong>also handles gross settlement of eligible interbank and customer payment orders. It is therefore useful to distinguish a customer order settled individually from a net position originating in another system. Both can involve the settlement infrastructure without representing the same processing model.</p><p>The following diagram is a conceptual explanation of a standard MAD transfer. It does not specify domestic message formats, integration interfaces, settlement schedules, or the exact point at which a particular bank credits customers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z1Wlxq9IEXHClWilF4_AVQ.png" /></figure><p>The individual payment is exchanged and processed; aggregate SIMT net positions settle through SRBM.</p><p>For Atlas’s MAD 25,000 payment, CIH first processes the customer instruction. The payment item is exchanged through the selected domestic arrangement. Clearing establishes obligations, and settlement of the relevant net positions changes participating banks’ settlement balances. Banque Populaire processes the beneficiary credit and produces the applicable customer and operational records.</p><p>That description deliberately distinguishes the individual payment from the net amount settled. A clearing cycle can contain many payments in both directions and across many banks. Our MAD 25,000 item contributes to the calculation; it is not necessarily a standalone MAD 25,000 movement between central-bank accounts.</p><p>Consider a deliberately small clearing set containing only these three obligations:</p><p>CIH owes Banque Populaire MAD 100,000.</p><p>Banque Populaire owes Bank of Africa MAD 70,000.</p><p>Bank of Africa owes CIH MAD 40,000.</p><p>CIH pays 100,000 and receives 40,000, so its net position is a MAD 60,000 debit. Banque Populaire receives 100,000 and pays 70,000, so its net position is a MAD 30,000 credit. Bank of Africa receives 70,000 and pays 40,000, so it also has a MAD 30,000 credit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iRiYJrMiS6LOM7kS4BDYYw.png" /></figure><p>Three gross obligations totaling MAD 210,000 produce a MAD 60,000 net debit and matching net credits.</p><p>The three gross obligations total MAD 210,000. Their multilateral net positions require one net debit of MAD 60,000 and two net credits of MAD 30,000. The debits and credits balance.</p><p>Netting reduces the amounts that must be settled for this set of obligations. It does not reduce what customers receive: the underlying customer payments remain distinct items with their own amounts and references. Nor does MAD 210,000 represent a universal minimum prefunding requirement for gross settlement; incoming funds can be recycled, and actual liquidity needs depend on ordering and system design.</p><p><strong>4. Why batch clearing and real-time gross settlement both exist</strong></p><p>A payroll run and an urgent equipment purchase pose different operational problems. Payroll can contain thousands of relatively small items. An urgent corporate payment may need prompt interbank finality. Payment systems balance throughput, timing, liquidity, cost, and risk differently.</p><p>An automated clearing house (ACH) is an infrastructure for processing payment instructions. A common retail design batches items and settles net obligations later. That is a useful model for understanding deferred net settlement, not a universal definition of every service operated by an ACH.</p><p>Real-time gross settlement (RTGS) processes settlement individually, without netting each payment against opposing obligations as the basis for settlement. “Real-time” describes when processing occurs; “gross” describes how the obligation is settled. They answer different questions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lihMUqh3ZYmKvAch6wEyyg.png" /></figure><p>RTGS combines timing and calculation choices; a fast customer experience alone does not identify the settlement model.</p><p>Suppose Atlas makes a separate urgent MAD 1,200,000 payment to an equipment vendor at Bank of Africa. Assume, purely for this example, that the instruction is eligible and submitted for gross settlement through SRBM.</p><p>Atlas having sufficient funds in its customer account is only one requirement. CIH also needs sufficient available settlement liquidity, or an applicable permitted credit facility, to settle the interbank obligation. Customer deposits and a bank’s immediately usable settlement balance are not the same thing.</p><p>If an illustrative settlement account has only MAD 900,000 available, the payment is MAD 300,000 short of the amount needed. Depending on the system’s rules, an instruction may wait in a queue, be rejected, or require another permitted resolution. A queued payment has not settled merely because it passed format checks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jxo-GA8VFtcNkaziYiSypA.png" /></figure><p>Customer funds and interbank settlement liquidity are different requirements.</p><p>An incoming payment or permitted liquidity provision can change what is available. Once settlement succeeds, the receiving bank can process the beneficiary credit. The operational stages are linked, but they are not interchangeable.</p><p>Instant customer payments add another distinction. A recipient can receive usable funds very quickly while the participating institutions settle through a design that involves prefunding or deferred settlement. Other instant systems settle each payment immediately. You must inspect the scheme’s actual rules before inferring interbank settlement timing from the customer experience.</p><p>The same care applies to finality. Final settlement gives legal certainty under the applicable framework. It does not mean that an authorized subsequent payment returning value is impossible. That later payment is a new movement, not necessarily an unwinding of the original final settlement.</p><p><strong>5. Cross the border: why correspondent banking exists</strong></p><p>Atlas now owes Iberia Machines EUR 18,500 for production equipment. The supplier banks with fictional European Bank E. Atlas uses CIH in Morocco.</p><p>A MAD settlement balance at Bank Al-Maghrib does not give CIH a EUR balance at Bank E. Reaching the supplier requires an arrangement for paying in EUR and, where necessary, accessing the relevant foreign payment infrastructure.</p><p>Maintaining branches, memberships, operational teams, and liquidity in every market would be expensive. A bank can instead obtain services from another bank that already has suitable capabilities. This service arrangement is correspondent banking.</p><p>The bank providing the service is the correspondent. The bank receiving the service is the respondent. Services may include making and receiving payments, account maintenance, currency conversion, access to local clearing, and agreed liquidity facilities. Broader relationships can also support trade finance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R-YOe1MMsynj1kIBdPsq-g.png" /></figure><p>The respondent obtains agreed services from the correspondent; their relationship exists before any individual payment.</p><p>For our first international arrangement, assume CIH maintains a funded EUR account at Bank E, which also holds Iberia Machines’ account. Bank E is the correspondent and CIH is the respondent. The relationship already exists before Atlas submits its payment.</p><p>A reciprocal account is not required: Bank E need not open a MAD account at CIH for this arrangement to work. A bank can also use correspondents even where it has a presence abroad; the choice concerns access, services, currency, economics, and risk, not just geography.</p><p>“Correspondent” and “intermediary” describe different aspects of a bank. Correspondent describes a service relationship. Intermediary describes a position between other institutions in a particular payment chain. Here Bank E is both the correspondent and the beneficiary’s bank, so no additional intermediary is needed between them.</p><p>Correspondent access brings responsibilities. Banks need agreements, account and routing information, due diligence, liquidity management, and operational controls. Funds held at a correspondent also create exposure to that commercial bank. A communication connection alone does not supply these arrangements.</p><p><strong>6. One account, several perspectives</strong></p><p>Give CIH’s hypothetical EUR account at Bank E the illustrative reference EUR-ACCOUNT-A. This is a teaching label, not an IBAN or routing identifier.</p><p>For CIH, it is a Nostro: our account with another bank. For Bank E, it is a Vostro: another bank’s account with us. These are perspectives on the same serviced account relationship, not two pools of money that must be transferred between each other.</p><p>If the account has a positive EUR 200,000 balance, CIH has an asset: a claim on Bank E. Bank E has a corresponding liability to CIH. The meaning comes from who owns and services the account, not a universal rule that the account must use the servicing bank’s domestic currency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OmJsdHRXnIlq3O5E38HXYA.png" /></figure><p>CIH’s Nostro and Bank E’s Vostro describe the same account relationship from opposite sides.</p><p>CIH also needs internal records of that asset and its activity. The expression Mirror Nostro commonly refers to an internal representation used to track and reconcile the external account. Its exact ledger or subledger implementation depends on the bank. It is not a second external deposit and should not be described universally as an off-balance-sheet account.</p><p>Internal expected activity and the correspondent’s reported activity can differ temporarily. An outgoing payment might be recorded internally before the correspondent posts it; a fee might appear on the correspondent statement before the account holder has booked it. That is why a mirror is not a guarantee of perfect real-time synchronization.</p><p>The word Loro needs care. Some payment explanations use it for a third bank’s perspective — “their account with another bank.” Other banking glossaries use it as a synonym for Vostro. Treat it as terminology requiring context, not a universally distinct fourth account type. When precision matters, say explicitly: “CIH’s EUR account held at Bank E.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8TezxToFQc6TwRcmSXzNxQ.png" /></figure><p>An internal Nostro representation supports reconciliation; Loro terminology is not uniform across references.</p><p><strong>7. Follow the EUR payment through the accounts</strong></p><p>First isolate the account mechanics from FX. Assume Atlas has an eligible EUR account at CIH, starts with EUR 50,000, and pays EUR 18,500. CIH’s account at Bank E starts at EUR 200,000. Iberia Machines starts at EUR 10,000. Ignore fees and other activity.</p><p>CIH processes Atlas’s instruction and sends Bank E an instruction to pay the supplier using CIH’s EUR account. Bank E applies its controls, debits the account it maintains for CIH, and credits Iberia Machines.</p><p>After completion, Atlas has EUR 31,500. CIH’s external EUR balance has fallen to EUR 181,500. Iberia Machines has EUR 28,500.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*urq2PYOV0u341cTCZL0GUA.png" /></figure><p>The customer deposit and Nostro asset decrease at CIH; Bank E reallocates liabilities to credit the supplier.</p><p>The simplified completed entries reveal both sides. At CIH, debit the customer deposit liability EUR 18,500 and credit the Nostro asset EUR 18,500. At Bank E, debit the liability owed to CIH EUR 18,500 and credit the supplier deposit liability EUR 18,500. Actual systems may use intermediate clearing or suspense entries; these are the final economic effects, not a prescribed posting sequence.</p><p>Bank E’s debit and CIH’s asset credit describe the same reduction from different accounting perspectives. They do not indicate that the money was deducted twice. Bank E reallocates liabilities between two accounts on its own books for this leg, so this example needs no additional payment to a separate beneficiary bank.</p><p>If Atlas instead pays from a MAD account, add an FX transaction explicitly. At a fictional rate of MAD 11 per EUR, the principal debit would be MAD 203,500. The receiving amount remains EUR 18,500, before any separately defined charges. FX pricing, accounting, currency permissions, and customer eligibility require their own controls. A MAD debit does not mechanically create EUR liquidity at the correspondent.</p><p>Add a local correspondent and a separate beneficiary bank</p><p>Now consider an alternative arrangement for the same invoice, not an additional payment. Assume CIH uses Attijariwafa bank as a local correspondent for this transaction. Attijariwafa bank maintains a EUR account at Bank E, and Iberia Machines banks at Bank F.</p><p>For clarity, assume CIH already holds sufficient EUR in an agreed account at Attijariwafa bank. No domestic MAD clearing leg or FX conversion is needed in this variant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*01ovAolz1EjF0QomadyaDg.png" /></figure><p>Each institution acts through its own relationships; additional banks do not necessarily mean additional currency conversions.</p><p>CIH instructs Attijariwafa bank under their agreed service arrangement. Attijariwafa bank uses its own EUR relationship with Bank E for the onward payment. Bank E debits that account and makes an onward EUR payment to Bank F through an appropriate EUR arrangement. Bank F receives the relevant payment and settlement evidence and processes the supplier credit.</p><p>CIH is not directly operating Attijariwafa bank’s account at Bank E. Each bank acts within its own mandates and relationships. If funding were provided in MAD instead, a separately agreed MAD funding and FX process would be required; we cannot label a Moroccan domestic payment as EUR settlement.</p><p>Adding banks introduces more account relationships, controls, and reconciliation points. It does not automatically introduce another currency conversion at each hop. A EUR payment can remain in EUR across several institutions.</p><p><strong>8. Where SWIFT fits — and where settlement happens</strong></p><p><strong>SWIFT </strong>provides financial messaging services that allow institutions to exchange instructions and information securely. It does not hold the customer’s payment amount or settle it merely by delivering a message.</p><p>In the direct example, the communication tells Bank E what CIH wants done. The account debit and supplier credit occur in Bank E’s books. In the indirect example, additional banks and possibly a foreign settlement system contribute their own processing and ledger events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DnKs6A9vDsA25yw8qiqojg.png" /></figure><p><strong>SWIFT </strong>carries the instruction; account movements occur at the bank or settlement infrastructure executing it.</p><p>Do not draw <strong>SWIFT </strong>as a box containing money between two bank accounts. Draw the instruction separately from the account movements it requests. Likewise, a technical acknowledgment establishes something about communication or message processing; it is not automatically proof of beneficiary credit.</p><p>The sending bank chooses a usable route from its operational knowledge: currency, account relationships, beneficiary details, settlement instructions, reachability, liquidity, timing, and applicable restrictions. An onward bank may make routing decisions for its own leg. <strong>SWIFT </strong>transports messages to addressed destinations; it does not independently invent the commercial relationships needed to fund a payment.</p><p>Domestic Moroccan processing and cross-border communication must remain distinct. We have not assumed that a SIMT payment uses <strong>SWIFT</strong>, or that a domestic interface accepts any particular international message format. A banking application can connect to multiple channels and adapters while keeping a coherent internal record of the customer’s payment.</p><p>This is where message standards will become useful in a later article. They provide structured ways to express participants, amounts, instructions, and reports. Understanding the underlying business events lets us interpret that data correctly instead of treating a message name as proof that money moved.</p><p><strong>9. Completion requires evidence, not one vague status</strong></p><p>Return to the finance manager’s question: “Why was I debited if the supplier has not been paid?” The useful response starts by locating the last confirmed event.</p><p>Was the request authorized? Were funds reserved or actually posted? Did an external institution accept the instruction? Did the relevant settlement occur? Did the beneficiary bank post the credit? Has the bank received the report needed to confirm it?</p><p>These questions concern different evidence. In a multi-bank payment, one leg may be settled while a later leg remains pending. Even when interbank settlement has completed, the receiving bank may still have an account exception, a control hold, or a posting failure to resolve. Conversely, some products make funds available before final interbank settlement under their scheme rules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c10NcxnlIRAHqkbv3nQQbg.png" /></figure><p>Keep communication, settlement, posting, and reconciliation evidence separate to investigate safely.</p><p>Reconciliation connects the records. For the direct EUR example, CIH expects an EUR 18,500 reduction in its account at Bank E, linked to the outgoing payment. It compares its records with the correspondent’s reported account activity, using appropriate references, amount, currency, booking and value dates, and account identity.</p><p>Suppose the internal expected closing balance is EUR 181,500, but Bank E reports EUR 181,475. The EUR 25 difference needs investigation. If the report separately identifies an agreed EUR 25 fee, CIH can book that fee through the authorized process. It should not silently change the original payment amount merely to force a match.</p><p>A missing statement entry is also not proof of failure. It could reflect report timing, a reference mismatch, or an instruction that has not executed. Resending the payment without establishing what happened can create a duplicate. Reconciliation therefore supports both accounting accuracy and safe operational decisions.</p><p><strong>Rejection, cancellation, and return are different outcomes</strong></p><p>A <strong>rejection </strong>means a request was not accepted or executed at the relevant processing stage. It still requires checking whether an earlier customer debit or reservation needs release or correction.</p><p>A <strong>cancellation </strong>request asks the responsible institution to stop an instruction if it can still do so under the applicable rules. Sending the request does not prove success. If the relevant leg has already settled, simply deleting the instruction cannot restore the previous balances.</p><p>A return transfers value back after the original payment has progressed to a stage where returning funds is appropriate. It requires its own authority, processing, records, and correlation to the original payment. It does not necessarily reverse all fees or reproduce the original FX outcome.</p><p>An investigation is the operational process of finding the facts and arranging the permitted resolution. It can involve tracing references, obtaining evidence from another bank, resolving account details, or explaining a delay. It is not itself a movement of funds.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bce7b44eee0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka Transactions on the Consumer Side: From read_committed to Exactly-Once Processing]]></title>
            <link>https://medium.com/@youssefelmessbahi/kafka-transactions-on-the-consumer-side-from-read-committed-to-exactly-once-processing-9225111e2964?source=rss-573653523742------2</link>
            <guid isPermaLink="false">https://medium.com/p/9225111e2964</guid>
            <category><![CDATA[kafka-transactions]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[kafka-consumer]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[YOUSSEF EL MESSBAHI]]></dc:creator>
            <pubDate>Sun, 27 Sep 2026 22:01:01 GMT</pubDate>
            <atom:updated>2026-09-27T22:01:01.845Z</atom:updated>
            <content:encoded><![CDATA[<h3>How Kafka controls transactional visibility, hides aborted records, and atomically connects output records with consumed offsets in Spring Boot</h3><p>A Kafka producer writes a record to a partition.</p><p>The broker acknowledges it. The record now physically exists in the partition log.</p><p>Can a consumer read it?</p><p>The answer is not always yes.</p><p>When Kafka transactions are involved, physical storage and consumer visibility become two different things. A record may already be replicated and available in the log while remaining invisible to consumers configured with read_committed.</p><p>That record may belong to:</p><ul><li>a transaction that is still open</li><li>a transaction that will eventually commit</li><li>or a transaction that has already been aborted.</li></ul><p>This is the first problem Kafka must solve on the consumer side:</p><blockquote><em>How can a consumer distinguish stable business records from transactional records that should not be visible?</em></blockquote><p>There is also a second, subtler problem.</p><p>Imagine that a Payment Service consumes an OrderConfirmed event, processes it, and publishes a PaymentRequested event. If the service crashes after publishing the output but before committing the input offset, Kafka delivers the order again after restart.</p><p>The same payment event may then be produced twice.</p><p>This creates the classic read–process–write problem:</p><pre>Read input<br>→ Process input<br>→ Write output<br>→ Commit input offset</pre><p>The output write and the offset commit are separate operations. A failure between them creates a duplicate-processing window.</p><p>Kafka transactions address both sides of this story:</p><ol><li>They determine which records a consumer is allowed to see.</li><li>They allow output records and consumed offsets to be committed atomically.</li></ol><p>To understand exactly-once processing, however, we must first examine what is actually stored inside a transactional Kafka partition.</p><h3>1. What a Kafka Consumer Sees Inside a Transactional Log</h3><p>Kafka partitions are append-only logs. Transactions do not replace that model with a separate transactional storage system.</p><p>Instead, Kafka adds transactional metadata to the records written into the existing partition log.</p><p>Consider a producer that writes two events:</p><pre>PaymentValidated<br>AccountDebitRequested</pre><p>When transactions are enabled, these records carry metadata that allows Kafka to associate them with a transactional producer. At the record-batch level, Kafka can identify information such as:</p><ul><li>the producer ID</li><li>the producer epoch</li><li>whether the batch is transactional</li><li>and whether it contains ordinary data or a transaction control marker.</li></ul><p>A simplified representation might look like this:</p><pre>Offset 0<br>PID=5<br>Producer epoch=0<br>Transactional=true<br>PaymentValidated</pre><pre>Offset 1<br>PID=5<br>Producer epoch=0<br>Transactional=true<br>AccountDebitRequested</pre><p>At this point, both records physically exist in the partition. Their visibility depends on what happens to the transaction.</p><h3>An ongoing transaction</h3><p>A transaction is ongoing while its final outcome has not yet been written to the affected partitions.</p><p>The log may contain its data records:</p><pre>Offset 0: PaymentValidated<br>Offset 1: AccountDebitRequested</pre><p>But there is no terminal commit or abort marker for that transaction yet.</p><p>Kafka cannot expose those records to a read_committed consumer because their final outcome is still unknown. The producer may commit the transaction, or it may abort it because of an application failure, timeout, or explicit rollback.</p><p>From a consumer’s perspective, these records are not stable yet.</p><pre>DATA → DATA → transaction still open</pre><p>Their physical presence does not make them committed.</p><h3>A committed transaction</h3><p>When the producer successfully completes the transaction, Kafka writes a commit control marker to every partition involved in it.</p><p>The simplified partition log becomes:</p><pre>Offset 0: PaymentValidated<br>Offset 1: AccountDebitRequested<br>Offset 2: COMMIT control marker</pre><p>The commit marker does not contain another business event. It records the outcome of the transaction for that partition.</p><p>Once the transaction is stable, a read_committed consumer can receive the two business records:</p><pre>PaymentValidated<br>AccountDebitRequested</pre><p>The application does not receive the commit marker as a normal ConsumerRecord. Kafka’s client and protocol machinery use it internally to interpret the transaction’s result.</p><h3>An aborted transaction</h3><p>Suppose the producer writes the two records but encounters a failure before completing its work.</p><p>Kafka may end the transaction with an abort marker:</p><pre>Offset 0: PaymentValidated<br>Offset 1: AccountDebitRequested<br>Offset 2: ABORT control marker</pre><p>A common misconception is that Kafka immediately removes offsets 0 and 1.</p><p>It does not.</p><p>The aborted records remain physically present in the append-only partition log. They disappear later only according to normal Kafka log-retention or compaction behavior — not because the transaction was aborted.</p><p>Their visibility is controlled when records are fetched.</p><p>A read_committed consumer must hide them, while a read_uncommitted consumer may receive them.</p><p>This gives us three possible transactional states:</p><pre>ONGOING<br>DATA → DATA<br>No final outcome yet</pre><pre>COMMITTED<br>DATA → DATA → COMMIT</pre><pre>ABORTED<br>DATA → DATA → ABORT</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1-guetTPRirY9D565JaLNw.png" /><figcaption><strong>Transaction States Inside a Kafka Partition</strong></figcaption></figure><p><em>Caption: Transactional records remain physically stored in the partition log. Their final transaction state determines whether a </em><em>read_committed consumer may observe them.</em></p><h3>read_uncommitted: expose the log without transactional isolation</h3><p>Kafka consumers use the following isolation-level property:</p><pre>spring.kafka.consumer.properties.isolation.level=read_uncommitted</pre><p>read_uncommitted is Kafka’s default consumer isolation level.</p><p>It allows the consumer to receive:</p><ul><li>non-transactional records</li><li>committed transactional records</li><li>records belonging to ongoing transactions</li><li>records belonging to transactions that later abort.</li></ul><p>Transaction control markers are internal records and are not exposed to application code as normal business events.</p><p>The important consequence is that a read_uncommitted consumer may act on data that never becomes part of a successfully committed transaction.</p><p>Imagine that a producer transaction writes:</p><pre>PaymentValidated<br>AccountDebitRequested</pre><p>The consumer reads PaymentValidated while the transaction is still open. A few moments later, the producer aborts the transaction.</p><p>The consumer has already processed a result that the producer intended to discard.</p><p>For audit logs, monitoring pipelines, or specialized low-level tools, this behavior may sometimes be acceptable. For business workflows requiring transactional consistency, it usually is not.</p><h3>read_committed: expose only stable transactional results</h3><p>A transaction-aware business consumer can instead use:</p><pre>spring.kafka.consumer.properties.isolation.level=read_committed</pre><p>This consumer can receive:</p><ul><li>committed transactional records</li><li>non-transactional records.</li></ul><p>It does not expose:</p><ul><li>records from ongoing transactions</li><li>records from aborted transactions</li><li>commit or abort control markers.</li></ul><p>The phrase read_committed can cause another misconception:</p><blockquote><em>A </em><em>read_committed consumer reads only records that were written transactionally.</em></blockquote><p>That is incorrect.</p><p>Non-transactional records have no transaction that could be committed or aborted, so they remain visible. The isolation level changes how transactional records are handled; it does not reject ordinary records.</p><p>Record in the partitionread_uncommittedread_committedNon-transactional recordVisibleVisibleCommitted transactional recordVisibleVisibleOngoing transactional recordPotentially visibleHiddenAborted transactional recordPotentially visibleHiddenCommit or abort control markerNot exposed to applicationNot exposed to application</p><h3>Physical presence is not application visibility</h3><p>This distinction is the foundation of transactional consumption:</p><pre>Stored in the partition<br>        ≠<br>Returned by consumer.poll()</pre><p>Kafka must consider more than whether the record exists or has been replicated.</p><p>For a read_committed consumer, Kafka must also determine:</p><ol><li>whether the record belongs to a transaction</li><li>whether that transaction has reached a final state</li><li>whether its final state is committed or aborted</li><li>whether an earlier transaction still makes the current part of the log unstable.</li></ol><p>The fourth condition is particularly important.</p><p>Kafka cannot always skip an ongoing transaction and immediately return later committed records. A transaction that starts earlier in the partition can temporarily prevent a read_committed consumer from seeing records that appear after it—even when those later records already belong to committed transactions.</p><p>The mechanism responsible for that boundary is the <strong>Last Stable Offset</strong>.</p><h3>2. Last Stable Offset: Why read_committed Must Sometimes Stop</h3><p>Filtering aborted records is only part of transactional consumption.</p><p>A read_committed consumer must also avoid records belonging to transactions whose final outcome is still unknown. Kafka enforces this through the <strong>Last Stable Offset</strong>, commonly called the <strong>LSO</strong>.</p><h3>Building the partition log</h3><p>Consider the order-events topic and one of its partitions, P2.</p><p>Its log contains records produced by three transactions:</p><pre>Offset 0: [PID=5, epoch=0, transactional=true]  OrderCreated<br>Offset 1: [PID=5, epoch=0, transactional=true]  OrderValidated</pre><pre>Offset 2: [PID=8, epoch=1, transactional=true]  PaymentInitiated</pre><pre>Offset 3: [PID=5, epoch=0, control=true]         COMMIT</pre><pre>Offset 4: [PID=9, epoch=0, transactional=true]  NotificationRequested<br>Offset 5: [PID=9, epoch=0, control=true]         COMMIT</pre><p>The records belong to three transactions:</p><pre>TX-1: offsets 0 and 1 → committed at offset 3<br>TX-2: offset 2       → still open<br>TX-3: offset 4       → committed at offset 5</pre><p>At first sight, a read_committed consumer should be able to read:</p><ul><li>offsets 0 and 1, because TX-1 committed</li><li>offset 4, because TX-3 committed</li></ul><p>But that is not what happens.</p><p>The consumer can initially receive only offsets 0 and 1.</p><p>The open transaction beginning at offset 2 prevents it from reading further—even though the transaction at offset 4 has already committed.</p><p>Why?</p><h3>The first unresolved transaction defines the visibility boundary</h3><p>Kafka must present a stable, ordered view of each partition.</p><p>At offset 2, Kafka knows that PaymentInitiated belongs to a transaction, but it does not yet know whether that transaction will commit or abort.</p><p>If Kafka returned the committed record at offset 4, the consumer would observe this sequence:</p><pre>Offset 0<br>Offset 1<br>Offset 4</pre><p>It would have jumped over offset 2 before Kafka knew whether that record should eventually become visible.</p><p>If TX-2 committed afterward, Kafka could not safely insert offset 2 back before an offset the consumer had already processed. The partition’s ordered view would be broken.</p><p>Kafka therefore stops read_committed consumers at the first unresolved transactional position.</p><p>In this example:</p><pre>First open transaction begins at offset 2<br>Stable visibility boundary = offset 2</pre><p>Offsets below 2 are stable. Offset 2 and everything after it remain temporarily unavailable to the read_committed consumer.</p><p>A practical way to reason about the LSO is:</p><blockquote><em>The LSO is the exclusive boundary up to which a </em><em>read_committed consumer can safely read.</em></blockquote><p>Therefore:</p><pre>Consumer may read: offset &lt; LSO<br>Consumer must stop: offset &gt;= LSO</pre><p>With the boundary at offset 2:</p><pre>Offset 0 → readable<br>Offset 1 → readable<br>Offset 2 → not readable yet<br>Offset 4 → not readable yet</pre><p>This avoids the common off-by-one confusion around the term “Last Stable Offset.” What matters operationally is that the first unresolved transactional offset acts as an exclusive visibility boundary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gBoReZCpqng6wU_P0uKAEg.png" /><figcaption><strong>LSO Blocking a Later Committed Transaction</strong></figcaption></figure><p><em>Caption: Although TX-3 has committed, its record remains temporarily invisible because the earlier TX-2 transaction is still open.</em></p><h3>LSO is not the same as the High Watermark</h3><p>The High Watermark and the LSO answer different questions.</p><p>The <strong>High Watermark</strong> represents the replication boundary: records below it have been replicated to the required in-sync replicas and are available for consumption according to Kafka’s replication guarantees.</p><p>The <strong>LSO</strong> represents the transactional-stability boundary: records below it are no longer blocked by an unresolved earlier transaction.</p><p>A partition can therefore have records that are safely replicated but not yet visible to a read_committed consumer.</p><p>Conceptually:</p><pre>Partition log<br>0    1    2    3    4    5    6<br>|---- stable ----|<br>          LSO</pre><pre>|----------- replicated -----------|<br>                         High Watermark</pre><p>A read_uncommitted consumer is primarily bounded by the High Watermark.</p><p>A read_committed consumer is bounded by the earlier of:</p><ul><li>the replication boundary</li><li>the transactional-stability boundary</li></ul><p>In simplified form:</p><pre>read_uncommitted boundary = High Watermark</pre><pre>read_committed boundary =<br>    min(High Watermark, Last Stable Offset)</pre><p>This is why changing isolation.level does more than filter records after they have been fetched. It can change how far into the partition the application is currently allowed to progress.</p><h3>What happens when the open transaction finishes?</h3><p>Suppose TX-2 eventually commits.</p><p>Kafka writes its commit control marker, and the transaction beginning at offset 2 is no longer unresolved. The stable boundary can advance.</p><p>The consumer can then receive:</p><pre>Offset 2: PaymentInitiated<br>Offset 4: NotificationRequested</pre><p>Both transactions are now committed.</p><p>If TX-2 aborts instead, Kafka writes an abort control marker. The stable boundary can still move forward, but the outcome is different:</p><pre>Offset 2 → skipped because its transaction aborted<br>Offset 4 → returned because its transaction committed</pre><p>Resolving the open transaction therefore unblocks later records regardless of whether the result is commit or abort.</p><p>The transaction does not need to succeed for the LSO to advance. It only needs to reach a final state.</p><h3>read_committed versus read_uncommitted</h3><p>Using the same partition, a read_uncommitted consumer can potentially receive:</p><pre>Offset 0: committed TX-1 record<br>Offset 1: committed TX-1 record<br>Offset 2: ongoing TX-2 record<br>Offset 4: committed TX-3 record</pre><p>It does not receive offsets 3 or 5 as application records because those are transaction control markers.</p><p>Before TX-2 is resolved, a read_committed consumer receives only:</p><pre>Offset 0: committed TX-1 record<br>Offset 1: committed TX-1 record</pre><p>It stops at the stable boundary.</p><p>The difference is therefore not merely:</p><pre>read_uncommitted → includes aborted records<br>read_committed   → excludes aborted records</pre><p>It is more accurately expressed as:</p><pre>read_uncommitted<br>→ may expose records without knowing their final transactional outcome</pre><pre>read_committed<br>→ exposes only a stable, ordered view of the partition</pre><h3>Why an open transaction can increase consumer lag</h3><p>An open transaction does not prevent producers from appending later records. The partition may continue growing while a read_committed consumer remains stopped at the LSO.</p><p>This can create an important operational situation:</p><pre>Log End Offset continues moving<br>LSO remains unchanged<br>read_committed consumer cannot progress</pre><p>The consumer appears to fall behind, even though later records may already belong to completed transactions.</p><p>Possible causes include:</p><ul><li>a producer transaction taking too long</li><li>an application starting a transaction but not completing it promptly</li><li>transaction-coordinator delays</li><li>an application failure waiting for the transaction timeout</li><li>an excessively large transactional unit of work.</li></ul><p>This is why transaction duration matters. Transactions should normally remain short and focused rather than surrounding slow external operations.</p><h3>The LSO guarantees stability, not transaction filtering by itself</h3><p>The LSO answers:</p><blockquote><em>How far can a </em><em>read_committed consumer safely read?</em></blockquote><p>It does not, by itself, answer:</p><blockquote><em>Which records below that boundary belong to aborted transactions?</em></blockquote><p>Once an open transaction is resolved, the LSO can move forward. If that transaction aborted, Kafka must still make sure its data records are not returned to the application.</p><p>That requires another mechanism: the broker’s aborted-transaction metadata and the consumer client’s filtering logic.</p><h3>3. How Kafka Hides Aborted Transactional Records</h3><p>The Last Stable Offset determines how far a read_committed consumer can safely progress.</p><p>But once an open transaction is resolved, Kafka still has another problem to solve:</p><blockquote><em>How does the consumer know which records belong to an aborted transaction?</em></blockquote><p>Kafka cannot determine this from the producer ID alone.</p><p>To understand why, let us extend the partition log from the previous section.</p><h3>The partition after the open transaction is aborted</h3><p>Initially, TX-2 was still open:</p><pre>Offset 0: [PID=5, epoch=0, transactional=true]  OrderCreated<br>Offset 1: [PID=5, epoch=0, transactional=true]  OrderValidated<br>Offset 2: [PID=8, epoch=1, transactional=true]  PaymentInitiated<br>Offset 3: [PID=5, epoch=0, control=true]         COMMIT<br>Offset 4: [PID=9, epoch=0, transactional=true]  NotificationRequested<br>Offset 5: [PID=9, epoch=0, control=true]         COMMIT</pre><p>Now suppose that TX-2 aborts. Kafka appends an abort control marker:</p><pre>Offset 6: [PID=8, epoch=1, control=true]         ABORT</pre><p>Later, the same producer begins another transaction and writes a new record:</p><pre>Offset 7: [PID=8, epoch=1, transactional=true]  PaymentRetried<br>Offset 8: [PID=8, epoch=1, control=true]         COMMIT</pre><p>The final partition looks like this:</p><pre>Offset 0: PID=5  OrderCreated<br>Offset 1: PID=5  OrderValidated<br>Offset 2: PID=8  PaymentInitiated<br>Offset 3: PID=5  COMMIT<br>Offset 4: PID=9  NotificationRequested<br>Offset 5: PID=9  COMMIT<br>Offset 6: PID=8  ABORT<br>Offset 7: PID=8  PaymentRetried<br>Offset 8: PID=8  COMMIT</pre><p>The important detail is that offsets 2 and 7 share the same producer identity:</p><pre>PID=8<br>Producer epoch=1</pre><p>But they do not have the same transactional outcome:</p><pre>Offset 2 → belongs to an aborted transaction<br>Offset 7 → belongs to a committed transaction</pre><p>Therefore, Kafka cannot use only the producer ID and producer epoch to decide whether a record must be skipped.</p><p>It must also identify the specific transactional range to which the record belongs.</p><h3>Why Kafka does not delete aborted records</h3><p>An aborted transaction does not physically remove its data records from the partition.</p><p>The partition remains an append-only log:</p><pre>DATA → DATA → ABORT</pre><p>Deleting arbitrary records immediately would complicate Kafka’s sequential storage model, replication, segment management, and recovery.</p><p>Instead, Kafka preserves the physical records and controls their logical visibility.</p><p>This separation is essential:</p><pre>Physical log<br>→ contains committed and aborted transactional records</pre><pre>Consumer-visible stream<br>→ contains only records allowed by the isolation level</pre><p>A read_uncommitted consumer may receive the aborted data record at offset 2.</p><p>A read_committed consumer must skip it while still accepting the later committed record at offset 7.</p><h3>The broker maintains an aborted-transaction index</h3><p>Kafka brokers organize partition data into log segments.</p><p>Alongside the normal segment files, the broker maintains transaction-index information for aborted transactions. A transaction-index file typically uses a name such as:</p><pre>00000000000000000000.txnindex</pre><p>Conceptually, an entry records enough information for the broker to identify an aborted transaction associated with a particular log range.</p><p>A simplified representation is:</p><pre>Aborted transaction<br>Producer ID: 8<br>First offset: 2<br>Abort marker offset: 6</pre><p>This means that the transactional records beginning at offset 2 and ending before the abort marker belong to an aborted transaction.</p><p>The record at offset 7 is not part of that aborted transaction, even though it was written by the same producer ID and producer epoch.</p><p>Conceptually:</p><pre>PID=8, offset 2 → inside aborted transaction → skip<br>PID=8, offset 7 → after abort marker          → accept</pre><p>The offset position and transaction boundary are therefore as important as the producer identity.</p><h3>The consumer does not open .txnindex files</h3><p>The .txnindex file belongs to the broker’s local storage.</p><p>A consumer application runs through Kafka’s network protocol. It cannot — and should not — access files stored on a broker’s filesystem.</p><p>The real flow is:</p><pre>Broker partition log<br>        ↓<br>Broker transaction index<br>        ↓<br>Kafka Fetch response<br>        ↓<br>Kafka consumer client<br>        ↓<br>Application poll()</pre><p>When a consumer sends a Fetch request using read_committed, the broker:</p><ol><li>determines the Last Stable Offset</li><li>reads eligible record batches from the partition log</li><li>consults its transaction-index information</li><li>adds metadata describing relevant aborted transactions to the Fetch response.</li></ol><p>The response therefore contains more than business records. It also carries the information the Kafka client needs to identify aborted transactional batches.</p><p>The broker does not send the .txnindex file itself.</p><p>It sends protocol metadata derived from that index.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qQPfr8EZZ0DSd-JVlUl8YA.png" /><figcaption><strong>How Kafka Filters Aborted Transactions</strong></figcaption></figure><p><em>Caption: The broker uses its internal transaction index to build aborted-transaction metadata. The consumer client uses that metadata before exposing records to the application.</em></p><h3>What the Fetch response tells the consumer</h3><p>At the protocol level, the broker can provide an aborted_transactions list containing information such as:</p><pre>Producer ID<br>First offset of the aborted transaction</pre><p>The consumer client combines this information with the transactional record batches and control markers present in the fetched data.</p><p>Conceptually, the client learns:</p><pre>PID=8 has an aborted transaction beginning at offset 2</pre><p>It then processes the fetched batches in offset order:</p><pre>Offset 0: PID=5 → return<br>Offset 1: PID=5 → return<br>Offset 2: PID=8 → aborted transaction begins → skip<br>Offset 3: COMMIT control marker → do not expose<br>Offset 4: PID=9 → return<br>Offset 5: COMMIT control marker → do not expose<br>Offset 6: PID=8 ABORT marker → aborted transaction ends<br>Offset 7: PID=8 → no longer inside aborted transaction → return<br>Offset 8: COMMIT control marker → do not expose</pre><p>The application consequently receives:</p><pre>Offset 0: OrderCreated<br>Offset 1: OrderValidated<br>Offset 4: NotificationRequested<br>Offset 7: PaymentRetried</pre><p>It does not receive:</p><pre>Offset 2: PaymentInitiated</pre><p>And it does not receive the control markers at offsets 3, 5, 6, or 8 as normal business records.</p><h3>Where does the filtering happen?</h3><p>It is tempting to say that the broker simply removes every aborted record before sending the response.</p><p>That explanation is incomplete.</p><p>The responsibilities are divided between the broker and the Kafka consumer client:</p><h3>The broker</h3><p>The broker:</p><ul><li>maintains the partition log</li><li>maintains transaction-index information</li><li>calculates the stable fetch boundary</li><li>adds aborted-transaction metadata to the Fetch response</li><li>returns the relevant record batches and protocol metadata.</li></ul><h3>The Kafka consumer client</h3><p>The client:</p><ul><li>interprets the aborted-transaction metadata</li><li>tracks which transactional batches belong to aborted transactions</li><li>processes control markers internally</li><li>excludes aborted records</li><li>excludes control records</li><li>returns only valid application records from poll().</li></ul><p>From the application’s perspective, the result is simple:</p><pre>ConsumerRecords&lt;String, PaymentEvent&gt; records =<br>        consumer.poll(Duration.ofSeconds(1));</pre><p>When the consumer uses read_committed, records does not contain the aborted PaymentInitiated event.</p><p>The filtering happens below the application API.</p><h3>Control records are processed, not delivered</h3><p>Commit and abort markers occupy offsets inside the partition log.</p><p>However, they are not ordinary domain events.</p><p>The Kafka client may inspect them internally to determine transaction boundaries, but it does not expose them as application-level ConsumerRecord values.</p><p>This explains why offsets returned to the application may appear to have gaps:</p><pre>Returned offsets:</pre><pre>0<br>1<br>4<br>7</pre><p>The missing positions may correspond to:</p><ul><li>aborted transactional data</li><li>commit control records</li><li>abort control records.</li></ul><p>A gap does not necessarily mean that Kafka lost records.</p><p>It may be the expected consequence of transactional filtering.</p><h3>Common misconceptions</h3><h3>“The consumer reads the broker’s transaction-index file”</h3><p>No. The broker reads its local index and exposes the required information through the Kafka protocol.</p><h3>“The broker deletes aborted records”</h3><p>No. The records remain physically stored until normal retention or compaction removes them.</p><h3>“All records with the same producer ID belong to the same transaction”</h3><p>No. A producer can execute multiple transactions. Transaction boundaries and offsets must also be considered.</p><h3>“The application receives commit and abort markers”</h3><p>No. Kafka processes control records internally and does not expose them as normal domain events.</p><h3>“read_committed only checks the transaction marker”</h3><p>Not by itself. Transactional consumption combines:</p><ul><li>the Last Stable Offset</li><li>aborted-transaction metadata</li><li>transactional batch metadata</li><li>internal processing of control markers.</li></ul><p>Together, these mechanisms create the stable record stream returned to the application.</p><h3>From visibility to processing atomicity</h3><p>At this point, Kafka can give the consumer a stable view:</p><ul><li>ongoing transactions remain behind the LSO</li><li>aborted records are skipped</li><li>committed transactional records are returned</li><li>non-transactional records remain visible</li><li>control records stay internal.</li></ul><p>But receiving only valid records does not automatically make the consumer’s own processing exactly once.</p><p>The consumer can still:</p><ol><li>read a valid record;</li><li>process it;</li><li>publish an output event;</li><li>crash before committing its input offset.</li></ol><p>After restart, Kafka delivers the same input again.</p><p>This creates the consumer-side duplicate-processing window.</p><h3>4. The Duplicate Window in Read–Process–Write</h3><p>Using read_committed ensures that the consumer does not receive aborted or unresolved transactional records.</p><p>However, it does not automatically make the consumer’s own processing exactly once.</p><p>Consider a Payment Service that consumes an order and publishes a payment request:</p><pre>order-events<br>    ↓<br>Payment Service<br>    ↓<br>payment-events</pre><p>The consumer performs four logical steps:</p><pre>READ → PROCESS → WRITE → COMMIT OFFSET</pre><p>For example:</p><ol><li>Read OrderConfirmed at offset 50.</li><li>Validate the order and build a payment request.</li><li>Publish PaymentRequested to payment-events.</li><li>Commit the consumed offset.</li></ol><p>Without a Kafka transaction, the output write and the offset commit are two independent operations.</p><p>That separation creates a failure window.</p><h3>When the output succeeds but the offset commit fails</h3><p>Suppose the Payment Service processes offset 50:</p><pre>Input record:<br>Topic: order-events<br>Partition: 2<br>Offset: 50<br>Event: OrderConfirmed</pre><p>The service publishes the output successfully:</p><pre>Output record:<br>Topic: payment-events<br>Event: PaymentRequested</pre><p>Before committing its consumer offset, the service crashes:</p><pre>READ offset 50<br>    ↓<br>PROCESS<br>    ↓<br>WRITE PaymentRequested<br>    ↓<br>CRASH<br>    ✕<br>COMMIT OFFSET</pre><p>The output event already exists in payment-events, but the consumer group still has no record that offset 50 was completed.</p><p>After restart, Kafka delivers offset 50 again:</p><pre>READ offset 50 again<br>    ↓<br>PROCESS again<br>    ↓<br>WRITE PaymentRequested again</pre><p>The result is duplicate processing and potentially a duplicate output event.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xnmZoVPpeQc1QsFysTMucw.png" /><figcaption><strong>The Duplicate-Processing Failure Window</strong></figcaption></figure><p><em>Caption: If the output is published but the input offset is not committed, Kafka redelivers the input after restart and the service may publish the output again.</em></p><h3>Why offset 51 is committed after processing offset 50</h3><p>A committed consumer offset does not represent the last record that was processed.</p><p>It represents the next offset the consumer group should read.</p><p>Therefore, after successfully processing offset 50, the consumer commits:</p><pre>51</pre><p>This means:</p><pre>Offsets 0–50 have been completed<br>Resume consumption from offset 51</pre><p>The relationship is:</p><pre>new OffsetAndMetadata(record.offset() + 1)</pre><p>For offset 50:</p><pre>50 + 1 = 51</pre><p>Committing 50 would incorrectly tell Kafka to resume from offset 50, causing that record to be delivered again.</p><h3>The possible failure points</h3><p>The consequences depend on when the service fails.</p><p>Failure momentOutput recordConsumer offsetResultBefore processingNot producedNot committedRecord is retriedDuring processingNot producedNot committedRecord is retriedAfter output, before offset commitProducedNot committedDuplicate-output riskAfter offset commitProducedCommittedProcessing completed</p><p>The dangerous case is:</p><pre>WRITE succeeded<br>OFFSET COMMIT failed</pre><p>Reversing the order does not solve the problem.</p><p>If the service commits the offset before publishing the output:</p><pre>READ<br>→ PROCESS<br>→ COMMIT OFFSET<br>→ CRASH<br>→ WRITE never happens</pre><p>Kafka considers the input processed, but the expected output was never published.</p><p>We have simply replaced duplicate output with lost output.</p><p>The underlying problem is not the order of the two operations. The problem is that they are not atomic.</p><h3>What exactly-once processing changes</h3><p>For a Kafka-to-Kafka pipeline, Kafka transactions can place the following operations inside one atomic unit:</p><pre>1. Produce the output record<br>2. Store the consumer group’s next offset</pre><p>For our example, the transaction contains:</p><pre>Produce PaymentRequested<br>+<br>Commit order-events partition 2 offset 51</pre><p>Kafka then applies one outcome to both operations.</p><h3>Transaction commits</h3><pre>PaymentRequested becomes committed<br>Offset 51 becomes committed</pre><p>A downstream read_committed consumer can observe the output, and the input consumer group continues from offset 51.</p><h3>Transaction aborts</h3><pre>PaymentRequested becomes aborted<br>Offset 51 is not committed</pre><p>The output record may physically exist in the Kafka log, but it remains invisible to downstream read_committed consumers.</p><p>Because the input offset was not committed, offset 50 is delivered again.</p><p>The listener may execute again, but the failed attempt did not leave a committed Kafka result.</p><p>This is the central atomicity guarantee:</p><pre>Output record + consumed offset<br>              ↓<br>     COMMIT TOGETHER<br>          or<br>      ABORT TOGETHER</pre><h3>Exactly-once result does not mean exactly-once execution</h3><p>A common misconception is:</p><blockquote><em>With exactly-once semantics, my listener method runs exactly once.</em></blockquote><p>That is not guaranteed.</p><p>Consider this sequence:</p><pre>Attempt 1:<br>Listener processes offset 50<br>Listener produces PaymentRequested<br>Transaction aborts</pre><pre>Attempt 2:<br>Listener processes offset 50 again<br>Listener produces PaymentRequested<br>Transaction commits</pre><p>The Java listener executed twice.</p><p>However, a downstream read_committed consumer observes only the record produced by the committed attempt.</p><p>Therefore, Kafka exactly-once processing means:</p><blockquote><em>One committed Kafka result, not necessarily one execution of application code.</em></blockquote><p>This distinction becomes critical when the listener performs an operation outside Kafka, such as calling a payment provider or updating an external database. Kafka cannot automatically roll back those side effects.</p><p>For a pure Kafka pipeline, however, output records and consumed offsets can be coordinated within the same Kafka transaction.</p><p>That is the mechanism Spring Kafka uses to implement transactional read–process–write processing.</p><h3>5. Exactly-Once Processing with Spring Kafka</h3><p>Spring Kafka can manage the complete transaction lifecycle around a @KafkaListener.</p><p>The recommended model is container-managed transactions:</p><pre>Listener container begins transaction<br>        ↓<br>Listener processes input<br>        ↓<br>KafkaTemplate produces output<br>        ↓<br>Container sends consumed offset to transaction<br>        ↓<br>Container commits transaction</pre><p>Application code focuses on business processing while the listener container coordinates the transactional boundaries.</p><h3>Required Spring Boot configuration</h3><p>A minimal configuration can look like this:</p><pre>spring.kafka.bootstrap-servers=localhost:9092</pre><pre># Consumer<br>spring.kafka.consumer.group-id=payment-service<br>spring.kafka.consumer.enable-auto-commit=false<br>spring.kafka.consumer.properties.isolation.level=read_committed</pre><pre># Producer transaction support<br>spring.kafka.producer.transaction-id-prefix=payment-service-${INSTANCE_ID:local}-</pre><p>Once a transactional ID prefix is configured, Spring Boot configures the producer for Kafka transactions.</p><p>Kafka transactional producers use idempotent production. Compatible settings such as acks=all are required by the transactional producer configuration.</p><p>They can be stated explicitly for clarity:</p><pre>spring.kafka.producer.acks=all<br>spring.kafka.producer.properties.enable.idempotence=true</pre><p>But these properties alone do not create exactly-once processing.</p><p>The essential requirement is that the output record and consumed offset participate in the same Kafka transaction.</p><h3>Why the transaction ID prefix must be unique</h3><p>Each application instance needs a unique transactional-ID prefix.</p><p>For example:</p><pre>payment-service-instance-1-<br>payment-service-instance-2-<br>payment-service-instance-3-</pre><p>If multiple live application instances use the same transactional identity, Kafka may fence an older producer when another producer claims that identity.</p><p>In Kubernetes or another horizontally scaled environment, the prefix can include a pod or instance identifier:</p><pre>spring.kafka.producer.transaction-id-prefix=payment-service-${HOSTNAME}-</pre><p>The exact naming strategy can vary, but active instances must not unintentionally reuse the same transactional IDs.</p><h3>The transactional listener</h3><p>The listener itself remains simple:</p><pre>@Component<br>public class OrderEventListener {<br>      private final KafkaTemplate&lt;String, PaymentRequested&gt; kafkaTemplate;<br>    public OrderEventListener(<br>            KafkaTemplate&lt;String, PaymentRequested&gt; kafkaTemplate) {<br>        this.kafkaTemplate = kafkaTemplate;<br>    }<br>    @KafkaListener(<br>            topics = &quot;order-events&quot;,<br>            groupId = &quot;payment-service&quot;<br>    )<br>    public void process(OrderConfirmed event) {<br>        PaymentRequested paymentRequested =<br>                new PaymentRequested(<br>                        event.orderId(),<br>                        event.customerId(),<br>                        event.amount()<br>                );<br>        kafkaTemplate.send(<br>                &quot;payment-events&quot;,<br>                event.orderId(),<br>                paymentRequested<br>        );<br>    }<br>}</pre><p>When the listener container is configured with a KafkaTransactionManager, Spring performs the surrounding transaction management.</p><p>Conceptually, Spring executes:</p><pre>BEGIN KAFKA TRANSACTION</pre><pre>READ OrderConfirmed<br>PROCESS business logic<br>SEND PaymentRequested<br>SEND CONSUMED OFFSET TO TRANSACTION</pre><pre>COMMIT KAFKA TRANSACTION</pre><p>The listener does not need to manually commit the consumer offset after every successful record.</p><h3>Configuring the listener-container transaction manager</h3><p>When Spring Boot detects a producer transaction-ID prefix, it can auto-configure a KafkaTransactionManager.</p><p>If the application uses a custom listener-container factory, the transaction manager can be connected explicitly:</p><pre>@Configuration<br>public class KafkaTransactionConfiguration {<br>      @Bean<br>    KafkaTransactionManager&lt;String, Object&gt; kafkaTransactionManager(<br>            ProducerFactory&lt;String, Object&gt; producerFactory) {<br>        return new KafkaTransactionManager&lt;&gt;(producerFactory);<br>    }<br>    @Bean<br>    ConcurrentKafkaListenerContainerFactory&lt;String, Object&gt;<br>    kafkaListenerContainerFactory(<br>            ConsumerFactory&lt;String, Object&gt; consumerFactory,<br>            KafkaTransactionManager&lt;String, Object&gt; kafkaTransactionManager) {<br>        var factory =<br>                new ConcurrentKafkaListenerContainerFactory&lt;String, Object&gt;();<br>        factory.setConsumerFactory(consumerFactory);<br>        factory.getContainerProperties()<br>                .setKafkaAwareTransactionManager(kafkaTransactionManager);<br>        return factory;<br>    }<br>}</pre><p>The amount of explicit configuration depends on Spring Boot auto-configuration and whether the application defines its own container factory.</p><p>The important architectural point is:</p><blockquote><em>The listener container must own the transaction surrounding listener execution.</em></blockquote><h3>What happens during successful processing?</h3><p>Suppose the listener receives:</p><pre>Topic: order-events<br>Partition: 2<br>Offset: 50<br>Consumer group: payment-service</pre><p>The container starts a Kafka transaction before calling the listener.</p><p>The listener publishes:</p><pre>Topic: payment-events<br>Key: order-784<br>Value: PaymentRequested</pre><p>When the listener returns successfully, Spring sends the next input offset to the transaction:</p><pre>Topic: order-events<br>Partition: 2<br>Offset: 51<br>Consumer group: payment-service</pre><p>The Kafka transaction now contains two related results:</p><pre>Output:<br>PaymentRequested</pre><pre>Consumer progress:<br>payment-service → order-events-2 → offset 51</pre><p>When Kafka commits the transaction, both become committed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qQPfr8EZZ0DSd-JVlUl8YA.png" /><figcaption><strong>Spring Kafka Transactional Read–Process–Write</strong></figcaption></figure><p><em>Caption: Spring Kafka commits the produced output and the consumer-group offset in the same transaction. Both become committed, or both are aborted.</em></p><h3>What happens when the listener fails?</h3><p>Suppose the business logic throws an exception:</p><pre>@KafkaListener(<br>        topics = &quot;order-events&quot;,<br>        groupId = &quot;payment-service&quot;<br>)<br>public void process(OrderConfirmed event) {<br>      PaymentRequested paymentRequested = createPayment(event);<br>    kafkaTemplate.send(<br>            &quot;payment-events&quot;,<br>            event.orderId(),<br>            paymentRequested<br>    );<br>    if (!event.isValid()) {<br>        throw new IllegalStateException(&quot;Invalid order&quot;);<br>    }<br>}</pre><p>The output send may already have occurred inside the transaction, but the transaction has not yet committed.</p><p>Because the listener throws an exception, the container aborts the transaction:</p><pre>PaymentRequested → aborted<br>Offset 51        → not committed</pre><p>A downstream consumer configured with:</p><pre>spring.kafka.consumer.properties.isolation.level=read_committed</pre><p>does not receive the aborted PaymentRequested record.</p><p>The input consumer group has not advanced to offset 51, so Kafka can deliver offset 50 again according to the configured retry and error-handling strategy.</p><h3>What sendOffsetsToTransaction() does internally</h3><p>At a lower level, the transactional producer can associate consumer offsets with its current transaction.</p><p>Conceptually:</p><pre>Map&lt;TopicPartition, OffsetAndMetadata&gt; offsets = new HashMap&lt;&gt;();<br><br>offsets.put(<br>        new TopicPartition(record.topic(), record.partition()),<br>        new OffsetAndMetadata(record.offset() + 1)<br>);<br>kafkaTemplate.sendOffsetsToTransaction(<br>        offsets,<br>        consumerGroupMetadata<br>);</pre><p>This does not immediately commit the offset.</p><p>It adds the offset update to the current Kafka transaction:</p><pre>Current transaction<br>├── PaymentRequested output record<br>└── payment-service offset 51</pre><p>When the transaction commits, Kafka commits both.</p><p>When the transaction aborts, neither becomes a committed result.</p><p>With container-managed transactions, Spring handles this step automatically after the listener completes successfully. That is safer and clearer than manually opening an independent transaction inside every listener method.</p><h3>The role of read_committed</h3><p>read_committed and producer transactions solve different parts of the problem.</p><h3>The transaction provides atomicity</h3><p>It atomically connects:</p><pre>Produced output<br>+<br>Consumed offset</pre><h3>read_committed provides visibility isolation</h3><p>It ensures downstream consumers do not observe:</p><ul><li>aborted output records</li><li>output from ongoing transactions</li><li>records beyond the stable transactional boundary.</li></ul><p>A more accurate description of Kafka exactly-once processing is therefore:</p><pre>Transactional producer<br>+<br>Consumed offsets included in the transaction<br>+<br>Downstream read_committed consumers</pre><p>Producer idempotence also protects eligible producer retries, but idempotence alone cannot atomically connect an output event with consumer progress.</p><h3>Exactly-once stops at Kafka’s boundary</h3><p>Kafka can atomically coordinate operations stored within Kafka:</p><ul><li>writing records to Kafka topics</li><li>committing consumer-group offsets to Kafka.</li></ul><p>It cannot automatically include external systems in the same Kafka transaction.</p><p>For example:</p><pre>@KafkaListener(topics = &quot;payment-events&quot;)<br>public void process(PaymentRequested event) {<br>    paymentProvider.charge(event);       // External HTTP call<br>    paymentRepository.save(event);       // Database transaction<br>    kafkaTemplate.send(&quot;payment-results&quot;, result);<br>}</pre><p>The following operations are not automatically part of the Kafka transaction:</p><pre>HTTP payment request<br>PostgreSQL update<br>Email<br>SMS<br>External REST call</pre><p>If the Kafka transaction aborts after an external payment provider has charged the customer, Kafka cannot undo that charge.</p><p>For those operations, the system still needs patterns such as:</p><ul><li>idempotency keys</li><li>transactional outbox</li><li>inbox or processed-event tables</li><li>database uniqueness constraints</li><li>retry-safe external APIs</li><li>compensation workflows.</li></ul><p>Kafka exactly-once semantics should therefore be described precisely:</p><blockquote><em>Kafka can provide exactly-once processing for a consume–process–produce flow when the consumed offsets and produced records are committed in the same Kafka transaction.</em></blockquote><p>It is not a universal exactly-once guarantee for every side effect performed by the application.</p><h3>Production considerations</h3><h3>Keep transactions short</h3><p>Long-running transactions delay stable visibility and can hold the LSO behind newer records.</p><p>Avoid placing slow external calls inside a Kafka transaction when possible.</p><h3>Watch transaction timeouts</h3><p>If processing exceeds transaction.timeout.ms, Kafka may abort the transaction.</p><p>The broker must also allow the producer’s configured transaction timeout.</p><h3>Watch max.poll.interval.ms</h3><p>This setting controls how long the consumer may go without calling poll() before the group considers it unresponsive.</p><p>It is separate from the Kafka transaction timeout:</p><pre>transaction.timeout.ms<br>→ maximum transaction lifetime</pre><pre>max.poll.interval.ms<br>→ maximum allowed delay between consumer polls</pre><h3>Propagate failures</h3><p>If processing fails, the exception must reach the listener container so that it can abort the transaction.</p><p>Silently catching an exception may cause Spring to treat processing as successful:</p><pre>try {<br>    processPayment(event);<br>} catch (Exception exception) {<br>    log.error(&quot;Processing failed&quot;, exception);<br>    // Dangerous if the listener returns normally<br>}</pre><p>If the error should abort the transaction, propagate it:</p><pre>try {<br>    processPayment(event);<br>} catch (Exception exception) {<br>    log.error(&quot;Processing failed&quot;, exception);<br>    throw exception;<br>}</pre><h3>Design retries and dead-letter handling explicitly</h3><p>An aborted transaction leaves the input offset uncommitted, so the record can be delivered again.</p><p>Production systems need a deliberate policy for:</p><ul><li>retry count</li><li>retry delay</li><li>non-retryable exceptions</li><li>dead-letter topics</li><li>poison messages</li><li>recovery after repeated failures.</li></ul><h3>Monitor transactional behavior</h3><p>Useful signals include:</p><ul><li>transaction-abort rate</li><li>transaction timeouts</li><li>producer-fencing exceptions</li><li>consumer lag</li><li>repeated listener executions</li><li>retry and dead-letter volume</li><li>long gaps between the LSO and the log end.</li></ul><h3>Final mental model</h3><p>Consumer-side Kafka transactions solve two different problems.</p><p>First, read_committed creates a stable view of the log:</p><pre>Open transaction   → wait<br>Committed record   → return<br>Aborted record     → skip<br>Control marker     → process internally</pre><p>Second, the processing transaction makes the output and consumer progress atomic:</p><pre>READ<br>→ PROCESS<br>→ WRITE OUTPUT<br>→ SEND OFFSET TO TRANSACTION<br>→ COMMIT</pre><p>The input read itself is not undone. If processing fails, the record can be read again.</p><p>What Kafka guarantees is that the failed attempt does not leave behind a committed Kafka output while also leaving the input offset uncommitted.</p><p>That is the real meaning of exactly-once read–process–write processing in Kafka.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9225111e2964" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Service Discovery with Spring Boot: How Eureka Works]]></title>
            <link>https://medium.com/@youssefelmessbahi/service-discovery-with-spring-boot-how-eureka-works-88e891ecc1ab?source=rss-573653523742------2</link>
            <guid isPermaLink="false">https://medium.com/p/88e891ecc1ab</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[eureka]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[eureka-server]]></category>
            <category><![CDATA[service-discovery]]></category>
            <dc:creator><![CDATA[YOUSSEF EL MESSBAHI]]></dc:creator>
            <pubDate>Sun, 27 Sep 2026 21:56:01 GMT</pubDate>
            <atom:updated>2026-09-27T21:56:01.969Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding dynamic service registration, discovery, load balancing, heartbeats, local caching, and high availability</h3><p>In a microservices architecture, service instances are created and removed dynamically.</p><p>An instance may be restarted, moved to another machine, replaced after a failure, or replicated when the application needs more capacity. As a result, its IP address and port cannot always be treated as permanent information.</p><p>Consider two services:</p><ul><li>order-service</li><li>product-service</li></ul><p>The Order Service needs to call the Product Service to retrieve product information. If it stores the address of one Product Service instance directly, the communication works only while that particular instance remains available at the same location.</p><p>This is the problem service discovery solves.</p><p>Instead of knowing the physical address of every Product Service instance, Order Service uses a stable logical name:</p><pre>product-service</pre><p>A service registry maintains the mapping between that name and the currently registered instances.</p><p>In this article, we will use Spring Cloud Netflix Eureka to understand:</p><ul><li>why hardcoded service addresses become a problem;</li><li>how services register with Eureka</li><li>how one service discovers another</li><li>how load balancing works with discovered instances</li><li>how Eureka detects unavailable instances</li><li>where registry information is stored</li><li>how multiple Eureka servers improve availability</li><li>why Eureka is not called for every business request</li><li>why a client may temporarily call an unavailable instance</li></ul><h3>1. Why Do We Need Service Discovery?</h3><p>Suppose Order Service communicates with Product Service using a hardcoded URL:</p><pre>public void callProductApi(String id) {<br>    RestTemplate restTemplate = new RestTemplate();<br>    String response = restTemplate.getForObject(<br>            &quot;http://localhost:8082/products/&quot; + id,<br>            String.class<br>    );<br>    System.out.println(<br>            &quot;Response from Product API call is: &quot; + response<br>    );<br>}</pre><p>This solution may be acceptable while Product Service has only one instance:</p><pre>Order Service<br>      |<br>      | http://localhost:8082<br>      v<br>Product Service</pre><p>The problem appears when Product Service is scaled:</p><pre>Product Service — Instance 1 — port 8082<br>Product Service — Instance 2 — port 8083<br>Product Service — Instance 3 — port 8084</pre><p>Order Service still knows only one address:</p><pre>http://localhost:8082</pre><p>Even though three Product Service instances are running, every request continues to target the first one.</p><p>This creates several problems.</p><h3>Single point of failure</h3><p>If the instance running on port 8082 becomes unavailable, Order Service can no longer call Product Service.</p><p>The other instances may still be running, but Order Service does not know their addresses:</p><pre>Order Service ──X──&gt; Product Service : 8082</pre><pre>Available instances:<br>Product Service : 8083<br>Product Service : 8084</pre><p>The service is available, but the caller cannot reach it.</p><h3>No load balancing</h3><p>Because Order Service always calls the same URL, all requests are sent to one Product Service instance.</p><pre>Order Service ─────&gt; Instance 1 : 8082<br>                     Instance 2 : 8083<br>                     Instance 3 : 8084</pre><p>Instance 1 may become overloaded while the other instances remain unused.</p><p>Starting multiple instances does not automatically distribute traffic. The caller first needs to know which instances exist and then select one of them.</p><h3>Tight coupling</h3><p>The hardcoded URL creates tight coupling between Order Service and the physical location of Product Service.</p><p>If Product Service changes its host or port, the address used by Order Service must also be updated.</p><p>For example:</p><pre>Old address: http://localhost:8082<br>New address: http://product-host:9090</pre><p>Without updating its configuration, Order Service cannot find the moved Product Service instance.</p><h3>Different environments use different addresses</h3><p>Development, testing, QA, and production environments may use different Product Service URLs:</p><pre># Development<br>product.service.url=http://localhost:8082</pre><pre># QA<br>product.service.url=http://product-service-qa:8082</pre><pre># Production<br>product.service.url=http://product-service-prod:8082</pre><p>These differences require careful configuration management and can easily lead to incorrect addresses being used in the wrong environment.</p><p>Externalizing the URL is useful, but Order Service still needs to know the exact location of Product Service.</p><h3>Instances can disappear dynamically</h3><p>A service instance may disappear because:</p><ul><li>the application was stopped</li><li>its container was replaced</li><li>the machine failed</li><li>a network problem occurred</li><li>the platform scaled the service down</li></ul><p>A hardcoded URL cannot automatically reflect these changes.</p><p>Order Service therefore needs a dynamic way to answer the following question:</p><blockquote><em>Which Product Service instances are currently available?</em></blockquote><p>This is the purpose of service discovery.</p><h3>Introducing a service registry</h3><p>With service discovery, Product Service instances register themselves with a central registry.</p><p>The registry stores information such as:</p><ul><li>service name</li><li>instance ID</li><li>IP address</li><li>hostname</li><li>port</li><li>status</li></ul><p>Order Service no longer needs to store one particular Product Service address. It asks the registry for instances registered under the logical name:</p><pre>product-service</pre><p>The interaction becomes:</p><pre>1. Product Service registers its instances.<br>2. Order Service asks for product-service.<br>3. The registry returns the known instances.<br>4. One Product Service instance is selected.<br>5. Order Service calls that instance.</pre><p>In the Spring Cloud ecosystem, Eureka can provide this service registry.</p><p>Eureka has two main roles:</p><h3>Eureka Server</h3><p>Eureka Server acts like a phonebook for services. It keeps information about registered service instances.</p><h3>Eureka Client</h3><p>A Eureka Client can:</p><ul><li>register itself with Eureka Server</li><li>retrieve registry information</li><li>discover instances of another service</li></ul><p>Both Order Service and Product Service can be Eureka clients:</p><ul><li>Product Service registers its instances.</li><li>Order Service retrieves those instances to call the Product Service.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c_m6d2cVkvShxOW4c0pDcQ.png" /><figcaption>HARDCODED URL VS SERVICE DISCOVERY</figcaption></figure><p><em>Figure 1 — With a hardcoded URL, Order Service knows only one Product Service instance. With Eureka, it discovers the instances through the stable logical name </em><em>product-service.</em></p><p>Service discovery therefore replaces a fixed physical dependency:</p><pre>Order Service → http://localhost:8082</pre><p>with a logical dependency:</p><pre>Order Service → product-service</pre><p>In the next section, we will create the Eureka Server that stores this mapping.</p><h3>2. Setting Up the Eureka Server</h3><p>Now that we understand why hardcoded URLs become a problem, let us create the component that will maintain the service registry.</p><p>Eureka Server acts like a phonebook for our microservices. It stores information about the service instances that register with it, including:</p><ul><li>service name</li><li>instance ID</li><li>IP address or hostname</li><li>port</li><li>status</li><li>additional metadata</li></ul><p>In our example, Product Service will register itself with Eureka Server. Order Service will then use Eureka to discover the available Product Service instances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OdC_lWiboWo-XGFVb4HjXw.png" /><figcaption>Eureka as a Service Registry</figcaption></figure><p><em>Figure 2 — Product Service instances register their addresses with Eureka Server. Order Service uses the logical name </em><em>product-service to discover them.</em></p><h3>2.1 Add the Eureka Server dependency</h3><p>Create a new Spring Boot application for Eureka Server and add the following dependency:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-cloud-starter-netflix-eureka-server&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>The dependency provides the components required to run a Eureka registry inside a Spring Boot application.</p><p>Because the dependency does not declare its own version directly, its version is resolved through the Spring Cloud dependency-management BOM:</p><pre>&lt;dependencyManagement&gt;<br>    &lt;dependencies&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-cloud-dependencies&lt;/artifactId&gt;<br>            &lt;version&gt;2023.0.1&lt;/version&gt;<br>            &lt;type&gt;pom&lt;/type&gt;<br>            &lt;scope&gt;import&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>    &lt;/dependencies&gt;<br>&lt;/dependencyManagement&gt;</pre><p>The Spring Cloud release train must always be compatible with the Spring Boot version used by the project. Here, 2023.0.1 is the version used in our example.</p><p>Using the BOM keeps the versions of the different Spring Cloud dependencies consistent. We therefore do not need to specify a separate version for the Eureka Server starter.</p><h3>2.2 Enable Eureka Server</h3><p>Add @EnableEurekaServer to the main application class:</p><pre>@SpringBootApplication<br>@EnableEurekaServer<br>public class EurekaServerApplication {<br>      public static void main(String[] args) {<br>        SpringApplication.run(<br>                EurekaServerApplication.class,<br>                args<br>        );<br>    }<br>}</pre><p>@SpringBootApplication starts the normal Spring Boot application.</p><p>@EnableEurekaServer activates the Eureka Server functionality and imports the configuration required to expose the registry and its dashboard.</p><p>The application is no longer only a standard Spring Boot service. It now acts as a service registry that can receive operations such as:</p><ul><li>service registration</li><li>lease renewal through heartbeats</li><li>deregistration</li><li>registry queries</li></ul><p>We will examine heartbeats and leases later. For now, the important point is that this application becomes the central place where service instances publish their locations.</p><h3>2.3 Configure the standalone server</h3><p>Add the following properties:</p><pre>spring.application.name=eureka-server<br>server.port=8761</pre><pre>eureka.client.register-with-eureka=false<br>eureka.client.fetch-registry=false</pre><p>Let us understand each property.</p><h3>Application name</h3><pre>spring.application.name=eureka-server</pre><p>This gives the application the logical name eureka-server.</p><h3>Server port</h3><pre>server.port=8761</pre><p>The Eureka Server will listen on port 8761, which is the conventional port commonly used in Eureka examples.</p><p>Its dashboard will be available at:</p><pre>http://localhost:8761</pre><h3>Do not register the standalone server</h3><pre>eureka.client.register-with-eureka=false</pre><p>A Eureka Server can also behave as a Eureka Client. This is useful when multiple Eureka servers register with and replicate information to one another.</p><p>For the moment, however, we have only one standalone server. There is no other Eureka Server with which it needs to register.</p><p>We therefore disable its client-side registration behavior.</p><h3>Do not fetch a registry</h3><pre>eureka.client.fetch-registry=false</pre><p>A normal Eureka Client retrieves registry information so that it can discover other services.</p><p>Our standalone Eureka Server does not currently need to retrieve a registry from another server. It is the only registry in the system.</p><p>For this reason, registry fetching is also disabled.</p><p>These two properties describe a standalone configuration:</p><pre>register-with-eureka=false<br>→ Do not register this server with another Eureka server.</pre><pre>fetch-registry=false<br>→ Do not retrieve registry information from another Eureka server.</pre><p>Later, when we create a Eureka cluster, both properties will be enabled because each Eureka Server will also behave as a client of its peers.</p><h3>2.4 Start the Eureka Server</h3><p>After starting the application, open:</p><pre>http://localhost:8761</pre><p>The Eureka dashboard displays information about:</p><ul><li>the server environment</li><li>registered application instances</li><li>instance status</li><li>general registry information</li></ul><p>At this point, the section titled <strong>Instances currently registered with Eureka</strong> should be empty.</p><p>That is expected. The registry is running, but no client application has registered yet.</p><pre>Eureka Server<br>└── No registered instances</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rBVDmL-SPkaF5n8yHaHApw.png" /><figcaption>Setting Up a Standalone Eureka Server</figcaption></figure><p><em>Figure 3 — The Eureka Server is running on port </em><em>8761, but its registry remains empty until a Eureka Client registers.</em></p><p>The next step is to configure Product Service as a Eureka Client and register it with this server.</p><h3>3. Registering Product Service with Eureka</h3><p>Now that Eureka Server is running, we can configure Product Service as a Eureka Client.</p><p>A Eureka Client performs two main operations:</p><ul><li>it registers its own instance with Eureka Server</li><li>it fetches the registry to discover other services.</li></ul><h3>3.1 Add the Eureka Client dependency</h3><p>Add the following dependency to Product Service:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-cloud-starter-netflix-eureka-client&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>The dependency version is resolved through the same Spring Cloud BOM used earlier.</p><h3>3.2 Configure Product Service</h3><p>Add the following properties:</p><pre>server.port=8082<br>spring.application.name=product-service</pre><pre>eureka.client.service-url.defaultZone=http://localhost:8761/eureka/</pre><pre>eureka.client.register-with-eureka=true<br>eureka.client.fetch-registry=true</pre><p>The most important property is:</p><pre>spring.application.name=product-service</pre><p>This name becomes the logical service identifier stored in Eureka. Other services will use product-service instead of its physical URL.</p><p>The defaultZone property tells the client where Eureka Server is located:</p><pre>eureka.client.service-url.defaultZone=http://localhost:8761/eureka/</pre><p>The remaining properties enable registration and discovery:</p><pre>eureka.client/be Brittanyfalse</pre><p>Actually use:</p><pre>eureka.client.register-with-eureka=true<br>eureka.client.fetch-registry=true</pre><p>Their responsibilities are different:</p><ul><li>register-with-eureka=true allows Product Service to publish its own instance information.</li><li>fetch-registry=true allows it to retrieve information about other registered services.</li></ul><p>Both values are true by default, so they can be omitted. Keeping them visible here makes the behavior easier to understand.</p><p>When Product Service starts, its Eureka client sends registration information containing values such as:</p><pre>Service name: product-service<br>Instance ID: host:product-service:8082<br>Hostname/IP: current host<br>Port: 8082<br>Status: UP</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tfn9CpScUD19pfTNmGIuvg.png" /><figcaption>PRODUCT SERVICE REGISTRATION</figcaption></figure><p><em>Figure 4 — At startup, Product Service sends its service name, instance ID, address, port, and status to Eureka Server.</em></p><p>After starting Product Service, open:</p><pre>http://localhost:8761</pre><p>The Eureka dashboard should now display PRODUCT-SERVICE under the registered instances.</p><p>The uppercase name shown on the dashboard is Eureka’s normalized representation of the application name. Other Spring services can continue using:</p><pre>product-service</pre><p>The same configuration can be added to Order Service so that it also registers with Eureka and fetches the registry.</p><p>At this point, both applications know where Eureka Server is — but Order Service still needs to use the registry to find Product Service.</p><h3>4. Discovering and Calling Product Service</h3><p>Without service discovery, Order Service calls one fixed address:</p><pre>public void callProductApi(String id) {<br>    RestTemplate restTemplate = new RestTemplate();<br>    String response = restTemplate.getForObject(<br>            &quot;http://localhost:8082/products/&quot; + id,<br>            String.class<br>    );<br>    System.out.println(<br>            &quot;Response from Product API call is: &quot; + response<br>    );<br>}</pre><p>This code depends directly on one Product Service instance.</p><p>With Eureka, Order Service can ask for all instances registered under product-service.</p><h3>4.1 Using DiscoveryClient</h3><p>Spring Cloud provides the DiscoveryClient abstraction:</p><pre>import org.springframework.cloud.client.ServiceInstance;<br>import org.springframework.cloud.client.discovery.DiscoveryClient;</pre><p>We can use it inside Order Service:</p><pre>@Service<br>public class ProductServiceClient {<br>    private final DiscoveryClient discoveryClient;<br>    private final RestTemplate restTemplate;<br>    public ProductServiceClient(DiscoveryClient discoveryClient) {<br>        this.discoveryClient = discoveryClient;<br>        this.restTemplate = new RestTemplate();<br>    }<br>    public void callProductApi(String id) {<br>        List&lt;ServiceInstance&gt; instances =<br>                discoveryClient.getInstances(&quot;product-service&quot;);<br>        URI uri = instances.get(0).getUri();<br>        String response = restTemplate.getForObject(<br>                uri + &quot;/products/&quot; + id, String.class<br>        );<br>        System.out.println(<br>                &quot;Response from Product API call is: &quot; + response<br>        );<br>    }<br>}</pre><p>The following line queries the discovery client using the logical service name:</p><pre>discoveryClient.getInstances(&quot;product-service&quot;);</pre><p>It may return several instances:</p><pre>http://10.0.2.17:8082<br>http://10.0.2.18:8082<br>http://10.0.2.19:8082</pre><p>The example chooses the first one:</p><pre>instances.get(0)</pre><p>This demonstrates discovery, but it is not real load balancing. It always selects the first instance and also fails if no instance is available.</p><p>With this manual approach, Order Service must implement the instance-selection logic itself.</p><h3>4.2 Using OpenFeign</h3><p>OpenFeign provides a cleaner way to declare the Product Service API.</p><p>Without service discovery, the client contains a configured URL:</p><pre>@FeignClient(<br>        name = &quot;product-service&quot;,<br>        url = &quot;${feign.client.product-service.url}&quot;<br>)<br>public interface ProductClient {<br>    @GetMapping(&quot;/products/{id}&quot;)<br>    String getProductById(@PathVariable(&quot;id&quot;) String id);<br>}</pre><p>With service discovery, we remove the fixed URL:</p><pre>@FeignClient(name = &quot;product-service&quot;)<br>public interface ProductClient {<br>    @GetMapping(&quot;/products/{id}&quot;)<br>    String getProductById(@PathVariable(&quot;id&quot;) String id);<br>}</pre><p>Here, product-service is not a hostname. It is the logical service name used to find instances through the discovery infrastructure.</p><p>Add Spring Cloud LoadBalancer:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-cloud-starter-loadbalancer&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>When the Feign method is called, the flow is:</p><ol><li>Feign receives the logical name product-service.</li><li>The discovery infrastructure provides the known instances.</li><li>Spring Cloud LoadBalancer selects one instance.</li><li>Feign constructs the physical URL.</li><li>The request is sent directly to the selected Product Service instance.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6LTtBz7DOiDcgd9AVteeiA.png" /><figcaption>DISCOVERY AND LOAD BALANCING WITH FEIGN</figcaption></figure><p><em>Figure 5 — Eureka provides the Product Service instances, Spring Cloud LoadBalancer selects one, and Feign sends the HTTP request.</em></p><p>This distinction is important:</p><pre>Eureka                     → discovers instances<br>Spring Cloud LoadBalancer → selects an instance<br>Feign                      → executes the HTTP request</pre><p>Feign simplifies the client code, but the selection still depends on the service instances obtained through discovery.</p><p>This raises several questions:</p><ul><li>How does Eureka know whether an instance is up or down?</li><li>Where does Eureka store the registrations?</li><li>What happens when an instance stops without deregistering?</li></ul><h3>5. How Eureka Tracks Service Instances</h3><p>Registering an instance once is not enough. If Product Service crashes later, Eureka needs a way to determine that its registration is no longer valid.</p><p>Eureka handles this through deregistration, heartbeats, leases, and eviction.</p><h3>5.1 Graceful deregistration</h3><p>When Product Service shuts down gracefully, its Eureka client sends a deregistration request to Eureka Server.</p><p>Eureka can then remove that instance from the registry without waiting for its lease to expire.</p><pre>Product Service → Deregistration request → Eureka Server</pre><p>This works only when the application has enough time to complete its shutdown process.</p><p>If the process crashes, the machine fails, or the network connection is lost, the client may be unable to send the deregistration request.</p><p>Eureka must therefore detect the failure another way.</p><h3>5.2 Heartbeats and leases</h3><p>A Eureka Client periodically sends a heartbeat — also called a lease renewal — to Eureka Server.</p><p>The default renewal interval is normally 30 seconds:</p><pre>eureka.instance.lease-renewal-interval-in-seconds=30</pre><p>Each successful heartbeat tells Eureka:</p><blockquote><em>This instance is still renewing its registration.</em></blockquote><p>If Eureka stops receiving renewals for longer than the configured lease-expiration duration, the lease becomes eligible for eviction.</p><p>The default expiration duration is normally 90 seconds:</p><pre>eureka.instance.lease-expiration-duration-in-seconds=90</pre><p>The relationship is:</p><pre>Registration<br>     ↓<br>Heartbeat received<br>     ↓<br>Lease renewed<br>     ↓<br>No heartbeat for the expiration duration<br>     ↓<br>Instance becomes eligible for eviction</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ibWPcMrUfZaBG6wPHlvgpQ.png" /><figcaption>REGISTRATION, HEARTBEAT, AND EVICTION LIFECYCLE</figcaption></figure><p><em>Figure 6 — A client registers once, renews its lease periodically, and becomes eligible for eviction when renewals stop.</em></p><h3>5.3 Eviction does not happen immediately</h3><p>Lease expiration and eviction are related, but they are not the same event.</p><p>The server runs an eviction task periodically:</p><pre>eureka.server.eviction-interval-timer-in-ms=60000</pre><p>Therefore, an expired instance may remain visible until the next eviction cycle runs.</p><p>A simplified failure timeline is:</p><pre>Last heartbeat<br>      ↓<br>Lease-expiration duration passes<br>      ↓<br>Lease expires<br>      ↓<br>Eviction task runs<br>      ↓<br>Registration is removed</pre><p>For a fast local demonstration, the timings can be reduced:</p><pre># Product Service<br>eureka.instance.lease-renewal-interval-in-seconds=60<br>eureka.instance.lease-expiration-duration-in-seconds=5</pre><pre># Eureka Server<br>eureka.server.enable-self-preservation=false<br>eureka.server.eviction-interval-timer-in-ms=6000</pre><p>In this deliberately incorrect timing relationship, the client waits 60 seconds before renewing, but the lease expires after only 5 seconds. Eureka can therefore remove a Product Service instance even though it is still running.</p><p>This configuration is useful only for observing eviction quickly. It should not be used in production.</p><h3>5.4 Eureka self-preservation</h3><p>Eureka enables self-preservation by default.</p><p>When the server observes an abnormal reduction in heartbeats, it may interpret the situation as a network problem affecting many services rather than as many simultaneous service failures.</p><p>In that situation, Eureka limits eviction to avoid removing a large number of potentially healthy instances.</p><p>For a local eviction demonstration, it can be disabled:</p><pre>eureka.server.enable-self-preservation=false</pre><p>Disabling it makes eviction easier to observe, but it removes an important protection. It should not be treated as a normal production recommendation.</p><h3>5.5 Heartbeat is not complete application health</h3><p>A heartbeat confirms that the Eureka client can renew its lease. It does not automatically prove that:</p><ul><li>the database is reachable</li><li>every downstream dependency is available</li><li>the application can successfully process business requests.</li></ul><p>By default, a successfully registered instance is announced as UP. Application health can be propagated through Eureka health-check integration:</p><pre>eureka.client.healthcheck.enabled=true</pre><p>This allows the client to communicate more meaningful application status, but heartbeat renewal and business readiness remain different concepts.</p><h3>5.6 Where does Eureka store the data?</h3><p>Eureka Server stores its registry in memory.</p><p>Conceptually, it maintains entries similar to:</p><pre>PRODUCT-SERVICE<br>└── host:product-service:8082<br>    └── Lease&lt;InstanceInfo&gt;</pre><p>InstanceInfo contains instance metadata such as:</p><pre>Instance ID<br>Application name<br>IP address<br>Hostname<br>Port<br>Status<br>Health URL<br>Additional metadata</pre><p>The surrounding lease tracks renewal information, including the last successful renewal and lease duration.</p><p>A simplified representation is:</p><pre>Map&lt;String, Map&lt;String, Lease&lt;InstanceInfo&gt;&gt;&gt;</pre><p>The first key represents the application name, while the second identifies a particular instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ibWPcMrUfZaBG6wPHlvgpQ.png" /><figcaption>EUREKA IN-MEMORY REGISTRY</figcaption></figure><p><em>Figure 7 — Eureka organizes registered service instances in memory and associates every </em><em>InstanceInfo with a renewable lease.</em></p><p>Because the registry is held in memory, Eureka does not depend on a traditional database for service registrations. Instances continuously register and renew their leases, while Eureka peers can replicate registry changes.</p><p>However, this creates another important question:</p><blockquote><em>What happens if Eureka Server itself goes down?</em></blockquote><h3>6. What Happens If Eureka Server Goes Down?</h3><p>A single Eureka Server can become a single point of failure.</p><p>If it becomes unavailable:</p><ul><li>new service instances cannot register</li><li>existing clients cannot fetch registry updates</li><li>deregistrations and heartbeats cannot reach the server</li><li>clients continue using their last locally cached registry for some time.</li></ul><p>To improve availability, Eureka can run as a cluster of peer servers.</p><p>Assume that we have three Eureka servers:</p><pre>eureka-1:8761<br>eureka-2:8762<br>eureka-3:8763</pre><p>Each Eureka Server also acts as a Eureka Client. It registers with its peers, fetches their registries, and replicates registration changes.</p><h3>Configuring the first Eureka Server</h3><pre>spring.application.name=eureka-server<br>server.port=8761</pre><pre>eureka.instance.hostname=eureka-1<br>eureka.client.register-with-eureka=true<br>eureka.client.fetch-registry=true</pre><pre>eureka.client.service-url.defaultZone=\<br>http://eureka-2:8762/eureka/,\<br>http://eureka-3:8763/eureka/</pre><h3>Configuring the second Eureka Server</h3><pre>spring.application.name=eureka-server<br>server.port=8762</pre><pre>eureka.instance.hostname=eureka-2<br>eureka.client.register-with-eureka=true<br>eureka.client.fetch-registry=true</pre><pre>eureka.client.service-url.defaultZone=\<br>http://eureka-1:8761/eureka/,\<br>http://eureka-3:8763/eureka/</pre><h3>Configuring the third Eureka Server</h3><pre>spring.application.name=eureka-server<br>server.port=8763</pre><pre>eureka.instance.hostname=eureka-3<br>eureka.client.register-with-eureka=true<br>eureka.client.fetch-registry=true</pre><pre>eureka.client.service-url.defaultZone=\<br>http://eureka-1:8761/eureka/,\<br>http://eureka-2:8762/eureka/</pre><p>The application clients should also know about multiple Eureka servers:</p><pre>eureka.client.service-url.defaultZone=\<br>http://eureka-1:8761/eureka/,\<br>http://eureka-2:8762/eureka/,\<br>http://eureka-3:8763/eureka/</pre><p>If one server becomes unavailable, clients can communicate with another server in the cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RQnqHr7sYslqUzSTkuJwnw.png" /><figcaption>Eureka Peer Cluster</figcaption></figure><p><em>Figure 8 — Eureka servers operate as peers and replicate registration information. Clients are configured with multiple server addresses.</em></p><p>In production, the three nodes should run on different machines, containers, or failure zones. Running all of them on the same machine would not protect the registry from a machine-level failure.</p><p>Peer replication improves availability, but registry changes may take time to reach every server. Eureka provides an eventually consistent view rather than immediate strong consistency.</p><h3>A note about self-preservation</h3><p>Eureka includes a self-preservation mechanism. When the server receives far fewer heartbeats than expected, it may temporarily limit eviction because the problem could be a network failure affecting many healthy services.</p><p>For a local eviction demonstration, self-preservation may be disabled:</p><pre>eureka.server.enable-self-preservation=false</pre><p>This should not be copied blindly into production. Disabling it can cause Eureka to remove healthy instances during a temporary network problem.</p><h3>7. Does Every Request Call Eureka Server?</h3><p>A common misconception is that every service-to-service call requires two network hops:</p><pre>Order Service → Eureka Server → Product Service</pre><p>That is not how Eureka works.</p><p>Eureka Server participates in service registration and discovery, but it does not proxy the business request.</p><p>At startup, Order Service fetches the registry:</p><pre>eureka.client.fetch-registry=true</pre><p>The client stores the registry locally. By default, it periodically refreshes that local copy:</p><pre>eureka.client.registry-fetch-interval-seconds=30</pre><p>When Order Service needs to call Product Service, the flow is:</p><ol><li>Order Service reads the Product Service instances from its local registry.</li><li>Spring Cloud LoadBalancer selects one instance.</li><li>Feign sends the request directly to that instance.</li></ol><pre>Registry synchronization:</pre><pre>Order Service → Eureka Server<br>              fetch registry</pre><pre>Business request:</pre><pre>Order Service → Product Service<br>                direct request</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q78DKOttwGPERcw5EltFPg.png" /><figcaption>Eureka Is Not an Extra Hop</figcaption></figure><p><em>Figure 9 — Eureka synchronizes registry information with the client, but the business request goes directly from Order Service to Product Service.</em></p><p>This local cache avoids calling Eureka Server for every request. It also allows existing services to continue discovering known instances temporarily when Eureka Server becomes unavailable.</p><p>However, caching introduces another problem: the local registry may not always contain the latest state.</p><h3>8. What If the Local Registry Is Stale?</h3><p>Suppose Order Service has the following instances in its local registry:</p><pre>product-service:<br>- 10.0.2.17:8082<br>- 10.0.2.18:8082<br>- 10.0.2.19:8082</pre><p>Now imagine that the second instance stops unexpectedly:</p><pre>10.0.2.18:8082 → unavailable</pre><p>Eureka Server does not remove it immediately. It must first detect the missing heartbeats, wait for the lease to expire, and run the eviction task.</p><p>Even after the server removes the instance, Order Service may still have it in its local registry until the next registry refresh.</p><p>The timeline becomes:</p><pre>1. Product Service instance stops.<br>2. Its heartbeats stop.<br>3. Eureka waits for the lease to expire.<br>4. Eureka evicts the instance.<br>5. Order Service refreshes its local registry.<br>6. The instance disappears from the local cache.</pre><p>During this interval, Spring Cloud LoadBalancer may select the unavailable instance and the request can fail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wTQBKXjVKwZc_VLHvYt42g.png" /><figcaption>Stale Local Registry</figcaption></figure><p><em>Figure 10 — A failed instance can remain in the client’s local registry until Eureka detects the failure and the client refreshes its cache.</em></p><p>This behavior is a trade-off.</p><p>Without local caching, clients would need to contact Eureka Server for every request, increasing latency and making Eureka part of the business-request path.</p><p>With local caching:</p><ul><li>discovery is faster</li><li>Eureka is not called for every request</li><li>clients remain less dependent on the immediate availability of Eureka Server</li><li>registry information can temporarily be stale</li></ul><p>Reducing the registry-fetch interval can make updates reach clients sooner:</p><pre>eureka.client.registry-fetch-interval-seconds=10</pre><p>However, a shorter interval increases traffic to Eureka Server and still cannot eliminate stale information completely.</p><p>An instance can fail immediately after being selected, even if the registry was completely accurate at the moment of selection.</p><p>Service discovery therefore helps clients find available instances, but it cannot guarantee that every selected instance will remain reachable.</p><h3>Conclusion</h3><p>Service discovery solves a fundamental problem in microservices: service names are stable, but service instances are dynamic.</p><p>With Eureka:</p><ul><li>service instances register their addresses and metadata</li><li>clients discover services through logical names</li><li>heartbeats renew instance leases</li><li>expired registrations are eventually evicted;</li><li>registry information is stored in memory</li><li>clients cache the registry locally</li><li>Spring Cloud LoadBalancer selects an instance</li><li>Feign sends the request directly to that instance</li><li>multiple Eureka servers improve registry availability.</li></ul><p>The most important point is that Eureka does not sit between Order Service and Product Service for every request.</p><p>It maintains a continuously updated mapping:</p><pre>product-service<br>        ↓<br>currently known instances</pre><p>That mapping may temporarily be stale because registration, heartbeat detection, eviction, peer replication, and client refresh all require time.</p><p>This is not an accidental detail — it is the central trade-off that allows Eureka to provide fast, decentralized service discovery.</p><p>Eureka gives services a dynamic view of the system. Understanding how that view is created, cached, and updated is what allows us to use service discovery correctly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88e891ecc1ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>