Kafka Interview Questions and Answers Part 5 - Exactly-Once and Transactions

Kafka Interview Q&A · Part 5 of 10

In this post we are going to cover exactly-once and transactions: what exactly-once really means, how transactions fix crash duplicates, read_committed, writing from Kafka into a database, the outbox pattern, and producer fencing. These are 7 real Kafka interview questions for data engineers, asked the way they come up on a real project, and the last one is a scenario where the finance team needs account balances from payment events with no double counting.

Exactly-once is one of the most misunderstood Kafka topics. Managers ask for it, and many answers promise more than Kafka gives. Interviewers ask about it to see if you know exactly what Kafka guarantees, where that guarantee stops, and what you build yourself around it.

Part 5 of the Real Time Kafka Interview Questions and Answers series on TechBrothersIT.

The short answer

Say this first

Exactly-once in Kafka is three things together: the idempotent producer, transactions that write the output and the consumer offsets atomically, and read_committed consumers. It covers Kafka to Kafka. For a database, make the write idempotent or store the offset with the data, and use an outbox instead of dual writes.

Let's set up the cluster and some sample data

We run a local Apache Kafka 4.4 cluster in KRaft mode with 1 node, which is both the broker and the controller. Here are the two starting files: seed.py sends four payments, and read.py reads a topic twice, once with read_uncommitted and once with read_committed.

seed.py
import json
from confluent_kafka import Producer

p = Producer({'bootstrap.servers': 'localhost:9092',
              'enable.idempotence': True})
payments = [('p1', 'acct-1', 100), ('p2', 'acct-2', 50),
            ('p3', 'acct-1', -30), ('p4', 'acct-2', 20)]
for pid, acct, amount in payments:
    value = json.dumps({'id': pid, 'amount': amount})
    p.produce('payments', key=acct, value=value)
p.flush()
print('sent', len(payments), 'payments')
read.py
import sys
from confluent_kafka import Consumer

topic = sys.argv[1]
for level in ['read_uncommitted', 'read_committed']:
    c = Consumer({'bootstrap.servers': 'localhost:9092',
                  'group.id': f'check-{topic}-{level}',
                  'enable.auto.commit': False,
                  'auto.offset.reset': 'earliest',
                  'isolation.level': level})
    c.subscribe([topic])
    offsets, empty = [], 0
    while empty < 3:
        m = c.poll(1.0)
        if m is None:
            empty += 1
        elif not m.error():
            offsets.append(m.offset())
    c.close()
    print(f'{level}: {len(offsets)} records, offsets {offsets}')

First we run python seed.py to put four payments on the payments topic.

Terminal
$ python seed.py
sent 4 payments

The four payments are p1 to p4, on two accounts. Now we can start with the questions.

Question 1: Your manager asks for exactly-once processing. What does exactly-once really mean in Kafka?

Exactly-once means the effect of each input record shows up once in the output, even when a step fails and runs again. It does not mean the network delivers every message once. Kafka's default is at-least-once.

GuaranteeHow you get it
At most oncemay lose, never redeliverscommit offsets, then process
At least oncenever loses, may duplicateprocess, then commit: the default
Exactly onceeach effect onceidempotence + transactions + read_committed

Kafka builds exactly-once from three parts:

  • Idempotent producer - no duplicates from its own retries
  • Transactions - output plus consumer offsets, all or nothing
  • read_committed - consumers skip aborted data

Let's check the transaction protocol on our cluster with kafka-features.sh.

Terminal
$ kafka-features.sh --bootstrap-server localhost:9092 describe | awk '/transaction.version/ {print $2, $7, $8}'
transaction.version FinalizedVersionLevel: 2

transaction.version is at level 2, so KIP-890 is active. Java producers from 4.0 get an epoch bump on every transaction, so a late retry can't end up in the next one.

The scope is the catch: Kafka to Kafka, read, process, write. Kafka Streams gives you all of it with processing.guarantee=exactly_once_v2. Writing to a database or calling an API needs help from that side.

Interview tip

Tell the manager: exactly-once is a property of the whole pipeline, not one setting.

Question 2: A job reads from one topic and writes to another, and a crash produced duplicates. How do Kafka transactions fix it?

Let's see the bug first. plain.py copies the four payments to ledger-plain, then crashes before it commits its offsets. Then we run it again and read the output topic.

plain.py
import os, sys
from confluent_kafka import Consumer, Producer

c = Consumer({'bootstrap.servers': 'localhost:9092',
              'group.id': 'plain-copier',
              'group.instance.id': 'plain-copier-0',
              'enable.auto.commit': False,
              'auto.offset.reset': 'earliest'})
p = Producer({'bootstrap.servers': 'localhost:9092',
              'enable.idempotence': True})
c.subscribe(['payments'])
batch = c.consume(num_messages=4, timeout=15)
for m in batch:
    p.produce('ledger-plain', key=m.key(), value=m.value())
p.flush()
if '--crash' in sys.argv:          # simulate a crash right here
    print('crashed after writing', len(batch), 'records')
    os._exit(1)
c.commit(asynchronous=False)
print('wrote', len(batch), 'records, then committed offsets')
Terminal
$ python plain.py --crash
crashed after writing 4 records
$ python plain.py
wrote 4 records, then committed offsets
$ python read.py ledger-plain
read_uncommitted: 8 records, offsets [0, 1, 2, 3, 4, 5, 6, 7]
read_committed: 8 records, offsets [0, 1, 2, 3, 4, 5, 6, 7]

On restart it read the same four again. The output now has 8 records, and four are duplicates.

The fix is one transaction for both. Here is the sequence:

  • The job sets a transactional.id and calls init_transactions().
  • In each transaction, it produces the output, and send_offsets_to_transaction() adds the consumer offsets.
  • commit_transaction() makes both visible at once.

Now the same crash with txn.py, right before the commit, and then a restart.

txn.py
import logging, os, sys
from confluent_kafka import Consumer, Producer

logging.basicConfig(filename='client.log')
c = Consumer({'bootstrap.servers': 'localhost:9092',
              'group.id': 'ledger-writer',
              'group.instance.id': 'ledger-writer-0',
              'enable.auto.commit': False,
              'auto.offset.reset': 'earliest',
              'isolation.level': 'read_committed'})
p = Producer({'bootstrap.servers': 'localhost:9092',
              'transactional.id': 'ledger-writer-0',
              'logger': logging.getLogger('txn')})
p.init_transactions()
c.subscribe(['payments'])
batch = c.consume(num_messages=4, timeout=15)
p.begin_transaction()
for m in batch:
    p.produce('ledger', key=m.key(), value=m.value())
p.send_offsets_to_transaction(c.position(c.assignment()),
                              c.consumer_group_metadata())
if '--crash' in sys.argv:          # simulate a crash right here
    p.flush()
    print('crashed before the commit, after', len(batch), 'records')
    os._exit(1)
p.commit_transaction()
print('committed', len(batch), 'records and their offsets')
Terminal
$ python txn.py --crash
crashed before the commit, after 4 records
$ python txn.py
committed 4 records and their offsets

The restarted instance calls init_transactions() with the same ID, which aborts the open transaction. The consumer starts from the last committed offset, and four records are committed once. Let's read ledger with both isolation levels.

Terminal
$ python read.py ledger
read_uncommitted: 8 records, offsets [0, 1, 2, 3, 5, 6, 7, 8]
read_committed: 4 records, offsets [5, 6, 7, 8]

A read_committed consumer sees exactly 4 records, at offsets 5 to 8. The aborted four are still in the log, at 0 to 3, but marked as aborted.

Real project

group.instance.id gives static membership, so the restarted consumer takes over at once. And Kafka Streams with exactly_once_v2 does all of this for you.

Question 3: A consumer sees messages from a transaction that was aborted. What does isolation level read committed do?

Aborted records are not deleted. They stay in the log, followed by an abort marker. We saw it in Question 2: read_uncommitted returned 8 records, and read_committed skipped the aborted ones and returned 4.

The markers take offsets too. Let's check the end offset of ledger.

Terminal
$ kafka-get-offsets.sh --bootstrap-server localhost:9092 --topic ledger
ledger:0:10

It is ledger:0:10. Here is the whole log, with one marker at 4 and one at 9.

offset0123456789
in the logp1p2p3p4ABORTp1p2p3p4COMMIT
uncommittedp1p2p3p4·p1p2p3p4·
committed·····p1p2p3p4·

So on a transactional topic, never assume offsets have no gaps.

read_committed also stops at the first open transaction, the last stable offset. Let's leave a transaction open with hang.py, write a plain record after it, and read audit.

hang.py
import logging, os
from confluent_kafka import Producer

logging.basicConfig(filename='client.log')
txn = Producer({'bootstrap.servers': 'localhost:9092',
                'transactional.id': 'audit-writer',
                'logger': logging.getLogger('txn')})
txn.init_transactions()
txn.begin_transaction()
txn.produce('audit', value='written inside an open transaction')
txn.flush()
plain = Producer({'bootstrap.servers': 'localhost:9092'})
plain.produce('audit', value='plain record written after it')
plain.flush()
print('one transaction left open, then one plain record')
os._exit(0)                        # exit without commit or abort
Terminal
$ python hang.py
one transaction left open, then one plain record
$ python read.py audit
read_uncommitted: 2 records, offsets [0, 1]
read_committed: 0 records, offsets []

read_uncommitted sees both records. read_committed sees nothing, until that transaction commits, aborts, or times out.

The defaults are the trap.

isolation.level default
Java consumerread_uncommitted
librdkafka (Python client)read_committed

The Java consumer defaults to read_uncommitted, but librdkafka, the Python client, defaults to read_committed. Set it explicitly in every consumer.

Stuck transaction

If a hanging transaction blocks your consumers, kafka-transactions.sh can list transactions, find hanging ones, and abort them.

Question 4: The pipeline writes from Kafka into a database. Why is Kafka exactly-once not enough there, and what do you do instead?

Kafka transactions cover Kafka only. The database write and the offset commit are two systems. If the job writes the row and crashes before it commits the offset, the restart writes the row again: a double count.

So we fix it in the database. sink.py stores each payment with its ID as the primary key, plus its Kafka offset, in one database transaction. It never commits offsets to Kafka: on start, it reads the next offset from the database.

Let's run it with a crash after offset 1, and then restart it.

sink.py
import json, os, sqlite3, sys
from confluent_kafka import Consumer, KafkaException, TopicPartition

db = sqlite3.connect('bank.db')
db.execute('create table if not exists payments (id text primary key,'
           ' account text, amount int, kafka_offset int)')
start = db.execute('select coalesce(max(kafka_offset) + 1, 0)'
                   ' from payments').fetchone()[0]
print('start at offset', start)
c = Consumer({'bootstrap.servers': 'localhost:9092',
              'group.id': 'balance-sink', 'enable.auto.commit': False})
c.assign([TopicPartition('payments', 0, start)])
while (m := c.poll(3.0)) is not None:
    if m.error():                  # fail loudly: a restart is safe
        raise KafkaException(m.error())
    pay = json.loads(m.value())
    with db:   # one database transaction: the row and its offset
        new = db.execute('insert or ignore into payments values (?,?,?,?)',
                         (pay['id'], m.key().decode(), pay['amount'],
                          m.offset())).rowcount
    print('applied' if new else 'skipped duplicate', pay['id'])
    if '--crash' in sys.argv and m.offset() == 1:
        os._exit(1)                # simulate a crash
rows = db.execute('select account, sum(amount) from payments'
                  ' group by account order by account').fetchall()
print('balances:', rows)
Terminal
$ python sink.py --crash
start at offset 0
applied p1
applied p2
$ python sink.py
start at offset 2
applied p3
applied p4
balances: [('acct-1', 70), ('acct-2', 70)]

The first run applies p1 and p2. On restart it says start at offset 2, applies p3 and p4, and both balances are 70.

insert or ignore on the payment ID also makes it idempotent, so even a replay from offset 0 can't double-count. In a warehouse, it is a MERGE on the business key.

The rule

The write is idempotent, or the offsets, per partition, commit with the data. Ideally both.

Question 5: A service must update its database and publish an event together. How does the outbox pattern help?

Writing to the database and then to Kafka is a dual write. If the service crashes in between, or Kafka is down, one side has the change and the other doesn't.

With an outbox, the service writes only to its own database: the order row, and an event row in an outbox table, in one local transaction. Both exist, or neither.

Then a relay publishes the pending outbox rows, and marks only the ones Kafka acknowledged. Let's run service.py, then relay.py twice.

service.py
import json, sqlite3

db = sqlite3.connect('shop.db')
db.execute('create table if not exists orders (id text primary key,'
           ' amount int)')
db.execute('create table if not exists outbox (seq integer primary key,'
           ' topic text, key text, payload text, sent int default 0)')
event = {'type': 'OrderPlaced', 'order': 'o-1001', 'amount': 250}
with db:   # one local transaction: the order and its event
    db.execute("insert into orders values ('o-1001', 250)")
    db.execute('insert into outbox (topic, key, payload) values (?, ?, ?)',
               ('orders', 'o-1001', json.dumps(event)))
print('saved order o-1001 and its event in one transaction')
relay.py
import sqlite3
from confluent_kafka import Producer

db = sqlite3.connect('shop.db')
p = Producer({'bootstrap.servers': 'localhost:9092',
              'enable.idempotence': True})
rows = db.execute('select seq, topic, key, payload from outbox'
                  ' where sent = 0 order by seq').fetchall()
done = []
for seq, topic, key, payload in rows:
    p.produce(topic, key=key, value=payload,
              headers={'event_id': str(seq)},
              on_delivery=lambda err, msg, s=seq: err or done.append(s))
p.flush(30)
with db:   # mark only the events Kafka acknowledged
    db.executemany('update outbox set sent = 1 where seq = ?',
                   [(s,) for s in done])
print('published', len(done), 'of', len(rows), 'pending events')
Terminal
$ python service.py
saved order o-1001 and its event in one transaction
$ python relay.py
published 1 of 1 pending events
$ python relay.py
published 0 of 0 pending events

The first relay run publishes 1 of 1 pending events, and the second run finds nothing to send. Now let's read the event with its headers.

Terminal
$ kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic orders --from-beginning --max-messages 1 --formatter-property print.headers=true
The consumer rebalance protocol (KIP-848) is production-ready! Set group.protocol=consumer to try it
  out. See https://kafka.apache.org/documentation/#consumer_rebalance_protocol
event_id:1  {"type": "OrderPlaced", "order": "o-1001", "amount": 250}

After the 4.4 console consumer's banner line, we see event_id:1 in the header and the OrderPlaced payload.

The relay is at-least-once: if it crashes after publishing but before marking, it publishes again. So consumers dedupe on the event ID.

Production

The relay is usually change data capture: Debezium reads the outbox table from the database log, with no polling. We cover CDC in Part 7.

Question 6: A transactional producer fails with a fenced error after a restart. What is producer fencing?

Fencing is how Kafka stops zombies. Each transactional ID has an epoch. When an instance calls init_transactions(), the coordinator bumps the epoch and aborts any open transaction of the older instance. The consumer group metadata sent with the offsets adds a second fence, against a zombie that lost its partitions in a rebalance.

Let's see it with fence.py. The old instance opens a transaction and writes a record. Then a restarted instance starts with the same transactional ID, and the old one tries to commit.

fence.py
import logging
from confluent_kafka import KafkaException, Producer

logging.basicConfig(filename='client.log')
conf = {'bootstrap.servers': 'localhost:9092',
        'transactional.id': 'ledger-writer-0',
        'logger': logging.getLogger('txn')}
old = Producer(conf)               # the instance before the restart
old.init_transactions()
old.begin_transaction()
old.produce('ledger', key='acct-1', value='{"id": "p9", "amount": 5}')
old.flush()
new = Producer(conf)               # the restarted instance, same id
new.init_transactions()
print('new instance: init_transactions done')
try:
    old.commit_transaction()
except KafkaException as e:
    err = e.args[0]
    print('old instance commit:', err.name(), '| fatal:', err.fatal())
    print(err.str())
Terminal
$ python fence.py
new instance: init_transactions done
old instance commit: _FENCED | fatal: True
Failed to end transaction: Local: This instance has been fenced by a newer instance
$ python read.py ledger
read_uncommitted: 9 records, offsets [0, 1, 2, 3, 5, 6, 7, 8, 10]
read_committed: 4 records, offsets [5, 6, 7, 8]

The commit fails with _FENCED, and fatal: True. read_committed still sees 4 records: the record of the fenced transaction, at offset 10, was aborted.

A fenced error usually means one of these:

  • Zombie - an old pod still running during a rolling deploy
  • Same ID twice - two replicas with a hard-coded transactional.id

And the fix:

  • Unique, stable transactional.id - app name + pod ordinal
  • On fenced: close and stop - never retry with that producer
  • Short transactions - transaction.timeout.ms, 60 s by default
Java note

In Java, the same error is a ProducerFencedException.

Scenario 7: The finance team needs account balances from payment events with no double counting. How do you design it end to end?

Let's go through the pipeline from the source to the database:

  • Source - outbox + CDC, a unique payment ID on every event
  • Topic - RF 3, min.insync.replicas=2, acks=all + idempotence
  • Balances - Kafka Streams, exactly_once_v2, dedupe on payment ID, compacted output
  • Database sink - payment ID as primary key, offset in the same transaction
  • Prove it - nightly reconciliation, replay tests

Now let's test the sink. The payment service resends p2 after a timeout, then sends p5, and we run sink.py again.

resend.py
import json
from confluent_kafka import Producer

p = Producer({'bootstrap.servers': 'localhost:9092',
              'enable.idempotence': True})
# the payment service resends p2 after a timeout, then sends p5
for pid, acct, amount in [('p2', 'acct-2', 50), ('p5', 'acct-1', 25)]:
    value = json.dumps({'id': pid, 'amount': amount})
    p.produce('payments', key=acct, value=value)
p.flush()
print('sent p2 again, and p5')
Terminal
$ python resend.py
sent p2 again, and p5
$ python sink.py
start at offset 4
skipped duplicate p2
applied p5
balances: [('acct-1', 95), ('acct-2', 70)]

The sink starts at offset 4, skips the duplicate p2, applies p5, and acct-1 is now 95.

Producer idempotence can't catch that resend, because it is a new record. And exactly_once_v2 would count it too. That is why every step that counts checks the payment ID.

Prove it

Reconcile the balances against the source system every night, and test a replay from offset 0. The balances must not move.

Key points to remember

  • Exactly-once = idempotence + transactions + read_committed
  • send_offsets_to_transaction: output and offsets commit together
  • Aborted records stay in the log; markers take offsets
  • Databases: idempotent writes or offsets stored with the data
  • Outbox instead of dual writes; a unique transactional.id

The full script

Here is a Python script that writes the files and runs every command above in order against a local Kafka 4.4; run pip install confluent-kafka first.

Show the full script that writes the files and runs every step
Full script - Kafka 4.4 running locally, pip install confluent-kafka, then run it with Python
# ========================================================================
# Kafka Interview Q&A #5 - Exactly-once and transactions
# TechBrothersIT. Sample data is invented for teaching.
# Every step below was run on Apache Kafka 4.4.0 (KRaft mode, 1 node) with confluent-kafka 2.16.0;
# the outputs in the video and the blog post are the real outputs. To run it yourself (Linux, macOS or WSL):
#   1. Download Kafka 4.4.0 from kafka.apache.org, extract it, and put its bin folder on your PATH.
#   2. Start a local cluster (see the Kafka quickstart; node 1 listens on localhost:9092).
#   3. pip install confluent-kafka   then   python Kafka_Interview_QA_05_Code.py   in an empty folder.
# Steps that stop or start a broker say so in a comment: do that by hand at that point.
# ========================================================================

import os, subprocess

def write(path, text):
    os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
    with open(path, "w", encoding="utf-8") as f:
        f.write(text.strip("\n") + "\n")

def run(cmd, expect_error=False):
    print("\n$ " + cmd, flush=True)
    rc = subprocess.run(cmd, shell=True).returncode
    if rc != 0 and not expect_error:
        raise SystemExit("stopped: this command was expected to succeed")

# Step 0: files used by the steps
write('seed.py', """\
import json
from confluent_kafka import Producer

p = Producer({'bootstrap.servers': 'localhost:9092',
              'enable.idempotence': True})
payments = [('p1', 'acct-1', 100), ('p2', 'acct-2', 50),
            ('p3', 'acct-1', -30), ('p4', 'acct-2', 20)]
for pid, acct, amount in payments:
    value = json.dumps({'id': pid, 'amount': amount})
    p.produce('payments', key=acct, value=value)
p.flush()
print('sent', len(payments), 'payments')
""")
write('read.py', """\
import sys
from confluent_kafka import Consumer

topic = sys.argv[1]
for level in ['read_uncommitted', 'read_committed']:
    c = Consumer({'bootstrap.servers': 'localhost:9092',
                  'group.id': f'check-{topic}-{level}',
                  'enable.auto.commit': False,
                  'auto.offset.reset': 'earliest',
                  'isolation.level': level})
    c.subscribe([topic])
    offsets, empty = [], 0
    while empty < 3:
        m = c.poll(1.0)
        if m is None:
            empty += 1
        elif not m.error():
            offsets.append(m.offset())
    c.close()
    print(f'{level}: {len(offsets)} records, offsets {offsets}')
""")
run('kafka-topics.sh --bootstrap-server localhost:9092 --create --partitions 1 --topic payments')
run('kafka-topics.sh --bootstrap-server localhost:9092 --create --partitions 1 --topic ledger')
run('kafka-topics.sh --bootstrap-server localhost:9092 --create --partitions 1 --topic ledger-plain')
run('kafka-topics.sh --bootstrap-server localhost:9092 --create --partitions 1 --topic audit')
run('kafka-topics.sh --bootstrap-server localhost:9092 --create --partitions 1 --topic orders')

# Step 1: Four payments on the payments topic
run('python seed.py')

# Step 2: KIP-890: transaction.version 2 is active on this 4.4 cluster
run("kafka-features.sh --bootstrap-server localhost:9092 describe | awk '/transaction.version/ {print $2, $7, $8}'")

# Step 3: Without transactions: crash before the offset commit, restart, duplicates
write('plain.py', """\
import os, sys
from confluent_kafka import Consumer, Producer

c = Consumer({'bootstrap.servers': 'localhost:9092',
              'group.id': 'plain-copier',
              'group.instance.id': 'plain-copier-0',
              'enable.auto.commit': False,
              'auto.offset.reset': 'earliest'})
p = Producer({'bootstrap.servers': 'localhost:9092',
              'enable.idempotence': True})
c.subscribe(['payments'])
batch = c.consume(num_messages=4, timeout=15)
for m in batch:
    p.produce('ledger-plain', key=m.key(), value=m.value())
p.flush()
if '--crash' in sys.argv:          # simulate a crash right here
    print('crashed after writing', len(batch), 'records')
    os._exit(1)
c.commit(asynchronous=False)
print('wrote', len(batch), 'records, then committed offsets')
""")
run('python plain.py --crash')
run('python plain.py')
run('python read.py ledger-plain')

# Step 4: With a transaction: crash before commit_transaction, restart
write('txn.py', """\
import logging, os, sys
from confluent_kafka import Consumer, Producer

logging.basicConfig(filename='client.log')
c = Consumer({'bootstrap.servers': 'localhost:9092',
              'group.id': 'ledger-writer',
              'group.instance.id': 'ledger-writer-0',
              'enable.auto.commit': False,
              'auto.offset.reset': 'earliest',
              'isolation.level': 'read_committed'})
p = Producer({'bootstrap.servers': 'localhost:9092',
              'transactional.id': 'ledger-writer-0',
              'logger': logging.getLogger('txn')})
p.init_transactions()
c.subscribe(['payments'])
batch = c.consume(num_messages=4, timeout=15)
p.begin_transaction()
for m in batch:
    p.produce('ledger', key=m.key(), value=m.value())
p.send_offsets_to_transaction(c.position(c.assignment()),
                              c.consumer_group_metadata())
if '--crash' in sys.argv:          # simulate a crash right here
    p.flush()
    print('crashed before the commit, after', len(batch), 'records')
    os._exit(1)
p.commit_transaction()
print('committed', len(batch), 'records and their offsets')
""")
run('python txn.py --crash')
run('python txn.py')

# Step 5: read_uncommitted sees the aborted records, read_committed does not
run('python read.py ledger')

# Step 6: The log end offset includes the two transaction markers
run('kafka-get-offsets.sh --bootstrap-server localhost:9092 --topic ledger')

# Step 7: An open transaction blocks read_committed consumers at the last stable offset
write('hang.py', """\
import logging, os
from confluent_kafka import Producer

logging.basicConfig(filename='client.log')
txn = Producer({'bootstrap.servers': 'localhost:9092',
                'transactional.id': 'audit-writer',
                'logger': logging.getLogger('txn')})
txn.init_transactions()
txn.begin_transaction()
txn.produce('audit', value='written inside an open transaction')
txn.flush()
plain = Producer({'bootstrap.servers': 'localhost:9092'})
plain.produce('audit', value='plain record written after it')
plain.flush()
print('one transaction left open, then one plain record')
os._exit(0)                        # exit without commit or abort
""")
run('python hang.py')
run('python read.py audit')

# Step 8: Database sink: payment ID as primary key, offset stored with the row
write('sink.py', """\
import json, os, sqlite3, sys
from confluent_kafka import Consumer, KafkaException, TopicPartition

db = sqlite3.connect('bank.db')
db.execute('create table if not exists payments (id text primary key,'
           ' account text, amount int, kafka_offset int)')
start = db.execute('select coalesce(max(kafka_offset) + 1, 0)'
                   ' from payments').fetchone()[0]
print('start at offset', start)
c = Consumer({'bootstrap.servers': 'localhost:9092',
              'group.id': 'balance-sink', 'enable.auto.commit': False})
c.assign([TopicPartition('payments', 0, start)])
while (m := c.poll(3.0)) is not None:
    if m.error():                  # fail loudly: a restart is safe
        raise KafkaException(m.error())
    pay = json.loads(m.value())
    with db:   # one database transaction: the row and its offset
        new = db.execute('insert or ignore into payments values (?,?,?,?)',
                         (pay['id'], m.key().decode(), pay['amount'],
                          m.offset())).rowcount
    print('applied' if new else 'skipped duplicate', pay['id'])
    if '--crash' in sys.argv and m.offset() == 1:
        os._exit(1)                # simulate a crash
rows = db.execute('select account, sum(amount) from payments'
                  ' group by account order by account').fetchall()
print('balances:', rows)
""")
run('python sink.py --crash')
run('python sink.py')

# Step 9: Outbox: the order and its event in one local transaction, then the relay
write('service.py', """\
import json, sqlite3

db = sqlite3.connect('shop.db')
db.execute('create table if not exists orders (id text primary key,'
           ' amount int)')
db.execute('create table if not exists outbox (seq integer primary key,'
           ' topic text, key text, payload text, sent int default 0)')
event = {'type': 'OrderPlaced', 'order': 'o-1001', 'amount': 250}
with db:   # one local transaction: the order and its event
    db.execute("insert into orders values ('o-1001', 250)")
    db.execute('insert into outbox (topic, key, payload) values (?, ?, ?)',
               ('orders', 'o-1001', json.dumps(event)))
print('saved order o-1001 and its event in one transaction')
""")
write('relay.py', """\
import sqlite3
from confluent_kafka import Producer

db = sqlite3.connect('shop.db')
p = Producer({'bootstrap.servers': 'localhost:9092',
              'enable.idempotence': True})
rows = db.execute('select seq, topic, key, payload from outbox'
                  ' where sent = 0 order by seq').fetchall()
done = []
for seq, topic, key, payload in rows:
    p.produce(topic, key=key, value=payload,
              headers={'event_id': str(seq)},
              on_delivery=lambda err, msg, s=seq: err or done.append(s))
p.flush(30)
with db:   # mark only the events Kafka acknowledged
    db.executemany('update outbox set sent = 1 where seq = ?',
                   [(s,) for s in done])
print('published', len(done), 'of', len(rows), 'pending events')
""")
run('python service.py')
run('python relay.py')
run('python relay.py')

# Step 10: The event on the orders topic, with its event_id header
run('kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic orders --from-beginning --max-messages 1 --formatter-property print.headers=true')

# Step 11: A restarted instance with the same transactional.id fences the old one
write('fence.py', """\
import logging
from confluent_kafka import KafkaException, Producer

logging.basicConfig(filename='client.log')
conf = {'bootstrap.servers': 'localhost:9092',
        'transactional.id': 'ledger-writer-0',
        'logger': logging.getLogger('txn')}
old = Producer(conf)               # the instance before the restart
old.init_transactions()
old.begin_transaction()
old.produce('ledger', key='acct-1', value='{"id": "p9", "amount": 5}')
old.flush()
new = Producer(conf)               # the restarted instance, same id
new.init_transactions()
print('new instance: init_transactions done')
try:
    old.commit_transaction()
except KafkaException as e:
    err = e.args[0]
    print('old instance commit:', err.name(), '| fatal:', err.fatal())
    print(err.str())
""")
run('python fence.py')
run('python read.py ledger')

# Step 12: The payment service resends p2: the sink skips the duplicate
write('resend.py', """\
import json
from confluent_kafka import Producer

p = Producer({'bootstrap.servers': 'localhost:9092',
              'enable.idempotence': True})
# the payment service resends p2 after a timeout, then sends p5
for pid, acct, amount in [('p2', 'acct-2', 50), ('p5', 'acct-1', 25)]:
    value = json.dumps({'id': pid, 'amount': amount})
    p.produce('payments', key=acct, value=value)
p.flush()
print('sent p2 again, and p5')
""")
run('python resend.py')
run('python sink.py')
Next in this series

Part 6: Retention, Compaction and Storage

The sample data on this page is invented for teaching. Every terminal output is the real output of the command above it, run on Apache Kafka 4.4.0 in KRaft mode with confluent-kafka 2.16.0; topic IDs are masked. Part of the Real Time Kafka Interview Questions and Answers series on TechBrothersIT. Features, limits and their status (GA or preview) are current as of October 2026; check the official Apache Kafka documentation (kafka.apache.org) for anything you quote in an interview.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.