# Commits और Delivery Semantics — Apache Kafka: बुनियाद से Production तक Event Streaming

Source: https://www.geekswithgeeks.com/hi/kafka/kc-delivery-semantics

> At-most-once, at-least-once और exactly-once processing में से चुनें।

## आप कब commit करते हैं यह तय करता है क्या बिगड़ सकता है

यदि आप **प्रोसेसिंग से पहले commit** करते हैं, तो crash से records खो सकते हैं (**at-most-once**)। यदि **प्रोसेस करके फिर commit** करते हैं, तो crash से कुछ records दोबारा प्रोसेस हो सकते हैं (**at-least-once**), जो आम डिफ़ॉल्ट है और माँग करता है कि आपकी प्रोसेसिंग **idempotent** या de-duplicated हो। **Exactly-once** नतीजों के लिए अतिरिक्त तंत्र चाहिए (transactions, या record की key या offset उपयोग करने वाला idempotent sink)। महत्वपूर्ण काम के लिए auto-commit बंद करें और side effect सफल होने के बाद commit करें, synchronously या batches में।

## Manual-commit consumer loop (उदाहरण)

Database write सफल होने के बाद ही commit करें। बीच में process मरे तो record फिर पढ़ा जाता है, इसलिए `save_order` को दोहराव सहना चाहिए (जैसे `INSERT ... ON CONFLICT DO NOTHING`)।

```python
from confluent_kafka import Consumer

c = Consumer({"bootstrap.servers": "localhost:9092", "group.id": "billing",
              "enable.auto.commit": False, "auto.offset.reset": "earliest"})
c.subscribe(["orders"])
try:
    while True:
        msg = c.poll(1.0)
        if msg is None: continue
        if msg.error(): raise RuntimeError(msg.error())
        save_order(msg.key(), msg.value())      # idempotent write
        c.commit(message=msg)                   # commit AFTER success
finally:
    c.close()
```

## दोहराव के लिए डिज़ाइन करें

सावधान commits के बावजूद retries और rebalances किसी record को दो बार पहुँचा सकते हैं। प्राकृतिक अनोखी key (जैसे order ID) उपयोग करें ताकि वही record दोहराने का कोई अतिरिक्त असर न हो।

**Quiz:** कौन-सा क्रम at-least-once processing देता है?

- [ ] दो बार commit करें
- [ ] Offset commit करें, फिर प्रोसेस करें
- [ ] कभी commit न करें
- [x] Record प्रोसेस करें, फिर offset commit करें

*Answer:* Record प्रोसेस करें, फिर offset commit करें. प्रोसेसिंग और commit के बीच crash से दोबारा पढ़ना होता है, हानि कभी नहीं।
