0Pricing
Advanced Spring Boot 4: Event-Driven Architecture (Kafka) · Lezione

Gestire callback di invio e acknowledgment dei producer

Impari a reagire all'esito degli invii asincroni Kafka usando callback, CompletableFuture e la configurazione degli ack per garantire l'affidabilità della consegna.

Gestire callback di invio e acknowledgment dei producer è una lezione Advanced Spring Boot 4: Event-Driven Architecture (Kafka) gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Advanced Spring Boot 4: Event-Driven Architecture (Kafka), e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Advanced Spring Boot 4: Event-Driven Architecture (Kafka) include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

Why Send Results Matter

When you call KafkaTemplate.send(), the message is dispatched asynchronously. The call returns immediately, but the broker may not have stored the record yet.

To build reliable producers you must inspect the result of each send so you can log, retry, or alert on failures.

The CompletableFuture Result

In Spring Kafka, send() returns a CompletableFuture<SendResult<K,V>>.

  • SendResult holds the RecordMetadata (partition, offset, timestamp).
  • You attach a continuation to handle success or failure.
CompletableFuture<SendResult<String,String>> future =
    kafkaTemplate.send("orders", order.getId(), payload);

Attaching whenComplete

Use whenComplete to handle both outcomes in one place. The first argument is the result, the second is the exception (null on success).

future.whenComplete((result, ex) -> {
    if (ex == null) {
        var md = result.getRecordMetadata();
        log.info("Sent to partition {} offset {}", md.partition(), md.offset());
    } else {
        log.error("Send failed", ex);
    }
});

Reading RecordMetadata

On success, RecordMetadata tells you exactly where the record landed.

  • partition() — which partition received it.
  • offset() — its position in that partition.
  • timestamp() — broker-assigned timestamp.
RecordMetadata md = result.getRecordMetadata();
String location = md.topic() + "-" + md.partition() + "@" + md.offset();

Blocking for the Result

Sometimes you need a synchronous guarantee. Call get() with a timeout to block until the broker acknowledges.

Use this sparingly — it kills throughput, but it is useful in tests or critical writes.

SendResult<String,String> result =
    kafkaTemplate.send("orders", payload).get(10, TimeUnit.SECONDS);

The acks Configuration

Acknowledgment durability is controlled by the producer acks setting:

  • acks=0 — fire and forget, no guarantee.
  • acks=1 — leader writes, then acknowledges.
  • acks=all — leader plus all in-sync replicas acknowledge.

Configuring acks in Spring Boot

Set the strongest durability with acks=all in your application.yml.

spring:
  kafka:
    producer:
      acks: all
      properties:
        min.insync.replicas: 2

Trade-off: Latency vs Durability

Stronger acks mean higher latency.

  • acks=0 is fastest but loses data on broker failure.
  • acks=all is safest but waits for replica confirmation.

For financial events choose all; for high-volume metrics 1 may suffice.

Centralizing Callback Logic

Avoid duplicating callback code. Wrap sends in a helper method that always logs metadata and failures consistently.

public void sendTracked(String topic, String key, String value) {
    kafkaTemplate.send(topic, key, value)
        .whenComplete((res, ex) -> {
            if (ex != null) metrics.incrementFailures();
            else metrics.incrementSuccess();
        });
}

Handling Failures Gracefully

In the failure branch you can:

  • Persist the failed payload to a fallback store.
  • Increment a failure metric for alerting.
  • Schedule a retry on a separate executor.

Never swallow the exception silently.

Putting It Together

A robust producer combines acks=all, callback inspection, and failure handling. This gives you observability and delivery guarantees without blocking your main flow.

future.whenComplete((res, ex) -> {
    if (ex != null) deadLetterStore.save(payload);
});

Quick Check

Test your understanding of producer acknowledgments.

Recap

You learned to handle the asynchronous result of Kafka sends.

  • send() returns a CompletableFuture<SendResult>.
  • Use whenComplete to inspect metadata or failures.
  • acks controls the durability vs latency trade-off.
  • Centralize callbacks for consistent reliability handling.

Domande Frequenti

La lezione «Gestire callback di invio e acknowledgment dei producer» è gratuita?

Sì — il testo completo di «Gestire callback di invio e acknowledgment dei producer» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Advanced Spring Boot 4: Event-Driven Architecture (Kafka), passa a CoddyKit PRO. Il corso Advanced Spring Boot 4: Event-Driven Architecture (Kafka) include 4 lezioni in totale.

Cosa imparerò in «Gestire callback di invio e acknowledgment dei producer»?

Impari a reagire all'esito degli invii asincroni Kafka usando callback, CompletableFuture e la configurazione degli ack per garantire l'affidabilità della consegna. Eserciti Advanced Spring Boot 4: Event-Driven Architecture (Kafka) con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Advanced Spring Boot 4: Event-Driven Architecture (Kafka)?

Non è richiesta alcuna esperienza precedente. Advanced Spring Boot 4: Event-Driven Architecture (Kafka) su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.

Quanto tempo richiede la lezione «Gestire callback di invio e acknowledgment dei producer»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Advanced Spring Boot 4: Event-Driven Architecture (Kafka)?

Sì. Ogni lezione Advanced Spring Boot 4: Event-Driven Architecture (Kafka) include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Integrare Spring Kafka Starter
  2. Inviare messaggi con KafkaTemplate
  3. Personalizzare la configurazione dei produttori
  4. Gestire callback di invio e acknowledgment dei producer
← Torna a Advanced Spring Boot 4: Event-Driven Architecture (Kafka)