Skip to main content

Question 10 of 50

Can a Producer be a microservice?

Mid-levelSenior

Question

"Can a microservice be a Kafka Producer? How does that usually show up in code?"

What the interviewer wants to assess

Whether you connect the abstract concept of "Producer" with how it actually shows up in a microservices architecture — this isn't a question about a separate entity, it's about a role the service itself takes on.

Resposta rápida

Yes. In practice, the producer is almost always part of an existing microservice — it's not a separate piece of infrastructure. The payments service, for instance, besides exposing its API and persisting data, also publishes events to Kafka as a side effect of business operations, typically right after writing a state change to the database.

Resposta nível Sênior

"Producer" is a role, not a separate entity — any application that calls Kafka's produce API (directly or via a client like Spring Kafka) acts as a producer at that moment. In a microservices architecture, the most common pattern is: the service processes a business operation, persists the result to its database, and then publishes an event representing that fact — for example, the payments service writes "payment approved" to the database and publishes PagamentoAprovado to Kafka. This raises a real consistency problem known as dual write — what if the database write succeeds but the Kafka publish fails (or vice versa)? That problem is solved with the transactional outbox pattern — covered in Chapter 12 — which guarantees the event publish is atomic with the database write.

In-depth explanation

See "Relation to Java and Spring Boot" in Chapter 3 and Chapter 12 on transactions and the outbox pattern for the dual write problem.

Exemplo financeiro

The credit-granting microservice, when approving a limit, writes the decision to the decisoes_credito table and publishes the CreditoAprovado event in the same flow — ideally atomically via outbox, so that a network failure publishing to Kafka doesn't leave the database and Kafka inconsistent with each other.

"The Producer is a component separate from Kafka, like a proxy"

There's no generic "Producer service" running alongside Kafka. Producer is any application code that uses the Kafka client to publish — usually inside the domain microservice itself.

Pode vir a seguir

Expected follow-up: "what happens if the database write succeeds but the Kafka publish fails?" — which leads straight into the outbox pattern.