Integrating Kafka for real-time notifications in a Spring Boot social media application involves adding the Spring Kafka dependency, configuring broker and topic settings, and building a producer and consumer to publish and process notification events.
Key Points: • The spring-kafka dependency and a Kafka broker address are configured in application.yml, along with serializer/deserializer settings for the message payload. • A KafkaTemplate is used to publish notification events, such as "new follower" or "new comment," to a dedicated topic whenever the triggering action happens. • A @KafkaListener-annotated method consumes messages from that topic and processes them, for example by pushing a notification to the recipient's device or updating an in-app notification feed. • Partitioning the topic by user ID can help preserve per-user notification ordering while still allowing parallel consumption across users. • Error handling with a dead-letter topic ensures a malformed or failing notification event doesn't block the rest of the stream.
Example: When a user comments on a post, the app publishes a CommentNotification event to a notifications topic; a consumer service picks it up, looks up the post owner's device token, and sends a push notification, all decoupled from the original comment request so the commenter doesn't wait on notification delivery.
Code Example:
@Service
public class NotificationProducer {
private final KafkaTemplate<String, NotificationEvent> kafkaTemplate;
public void publish(NotificationEvent event) {
kafkaTemplate.send("notifications", event.getUserId(), event);
}
}
@Component
public class NotificationConsumer {
@KafkaListener(topics = "notifications", groupId = "notification-service")
public void consume(NotificationEvent event) {
pushService.send(event);
}
}Interview Tip: A concise interview answer is:
"I'd add the Spring Kafka dependency, configure the broker and topic in application.yml, then build a producer that publishes notification events with KafkaTemplate whenever a triggering action happens, and a @KafkaListener consumer that delivers the notification. Partitioning by user ID keeps per-user ordering, and a dead-letter topic handles malformed events without blocking the stream."