๐Ÿš€ Building a Microservice Architecture with Node.js and Kafka: Sending Order Completion Emails on Google Cloud โ˜๏ธ

๐Ÿš€ Building a Microservice Architecture with Node.js and Kafka: Sending Order Completion Emails on Google Cloud โ˜๏ธ

ยท

3 min read

Hey there! ๐Ÿ‘‹ Welcome to my blog, where we'll explore the exciting world of microservices, Node.js, and Kafka while leveraging the power of Google Cloud's Confluent Cloud to send delightful order completion emails to our users. ๐Ÿ“ง๐ŸŽ‰

Why Microservice Architecture?

Before we dive into the technical nitty-gritty, let's understand why microservice architecture is so popular and beneficial. ๐Ÿ—๏ธ Microservices are a way of designing applications as a collection of loosely coupled services, each responsible for a specific business function. This architecture enables teams to work independently, scale efficiently, and maintain better fault isolation, making it an excellent choice for modern web applications. ๐ŸŒ

The Magic of Node.js and Kafka ๐ŸŽฉ๐Ÿ˜

When it comes to building real-time, scalable applications, Node.js and Kafka make a dynamic duo. ๐Ÿค Node.js, with its non-blocking, event-driven architecture, is perfect for handling asynchronous operations in real-time. On the other hand, Kafka acts as a robust distributed message broker that ensures seamless communication between microservices. ๐Ÿ“จ๐Ÿ“จ

Setting Up Kafka with Confluent Cloud โ˜๏ธ

Confluent Cloud provides a straightforward and reliable way to set up Kafka and start building our microservice communication layer.

We'll walk through the steps to create a Kafka client using the kafkajs library and configure it to connect to Confluent Cloud brokers securely. ๐Ÿš€๐Ÿ”’

import { Kafka, EachMessagePayload } from "kafkajs";

const kafka = new Kafka({
  clientId: "email-service",
  brokers: ["po5hj-6ojv2.us-west3.gcp.confluent.cloud:9092"],
  ssl: true,
  sasl: {
    mechanism: "plain",
    username: "Username",
    password: "yyehi6kk+dj....",
  },
  connectionTimeout: 3000,
  enforceRequestTimeout: true,
});

Sending Order Completion Emails ๐Ÿ›’๐Ÿ“ง

We'll create a Node.js microservice responsible for handling order completion. Whenever a user successfully completes an order, this microservice will use Nodemailer to send personalized order completion emails to both the customer and the admin. ๐Ÿ’Œ๐ŸŽ

import { createTransport } from "nodemailer";

const transporter = createTransport({
  host: "mailhog",
  port: 1025,
});

Within our Kafka consumer, we'll define the logic to handle incoming messages from the "email_topic" and send the order completion emails using the Nodemailer transport we created. ๐Ÿ“จโœ‰๏ธ

const consumer = kafka.consumer({ groupId: "email-consumer" });

const run = async () => {
  await consumer.connect();
  await consumer.subscribe({ topic: "email_topic" });
  await consumer.run({
    eachMessage: async (message: EachMessagePayload) => {
      const order = JSON.parse(message.value.toString());

      // Send order completion email to customer
      await transporter.sendMail({
        from: "from@example.com",
        to: "to@example.com",
        subject: "An order has been completed",
        html: `Order #${order.id} has been completed.`,
      });

      // Send order completion email to admin
      await transporter.sendMail({
        from: "from@example.com",
        to: "admin@example.com",
        subject: "An order has been completed",
        html: `Order #${order.id} has been completed.`,
      });
    },
  });
  transporter.close();
};

run().catch(console.error);

Updating Order Status and Triggering Email Notification ๐Ÿ“๐Ÿ“จ

In our order completion function, we'll update the order status to indicate completion and produce a Kafka message containing the order details. This message will be consumed by our email microservice to trigger the email notification process. โœ…๐Ÿ“ค

export const ConfirmOrder = async (req: Request, res: Response) => {
  // Code to fetch and update order status...

  const value = JSON.stringify(order);

  // Produce a Kafka message containing the order details
  await producer.send({
    topic: "default",
    messages: [{ value }],
  });

  res.send({
    message: "success",
  });
};

Wrapping Up ๐ŸŽ๐ŸŽ‰

By combining the power of Node.js, Kafka, and Confluent Cloud, we've created a resilient and scalable microservice architecture to send order completion emails to our users. ๐Ÿ’Œ๐ŸŒ Whether you're a seasoned developer or just starting, leveraging these technologies will undoubtedly elevate your application development game. So, why wait? Let's get building! ๐Ÿ› ๏ธ๐Ÿ’ป

Feel free to leave your thoughts and questions in the comments below. Happy coding! ๐Ÿ˜Š๐Ÿ‘ฉโ€๐Ÿ’ป