Video in progress

Why should sending notifications (SMS, email, push) be split off from the main request and made asynchronous?

External providers are slow and unreliable: an SMS gateway can take 3 seconds to respond or return an error. If you put the notification on a queue and send it through a separate worker, the main operation finishes fast and retrying on failure is easy.

📖 Answer

The wrong way:

@Transactional
public Order placeOrder(OrderRequest req) {
    Order order = orderRepository.save(new Order(req));
    smsClient.send(req.phone(), "Buyurtma qabul qilindi"); // 3 seconds...
    return order;
}

The problems: if the SMS is slow, the order is slow too. If the SMS fails, the order is rolled back — the customer was ready to pay, and you lost the sale because of an SMS. On top of that, the transaction and the DB connection are held for those 3 seconds.

The right way: the order is saved, an OrderPlaced event is written to the queue, and the notification service picks it up and sends the SMS. If the provider is down, it retries several times with a delay; if that still fails, the message lands in the dead letter queue and someone looks at it.

Bonus: all channels are managed in one place. If a user has turned off SMS, if you shouldn't send messages at night, if one customer shouldn't get 10 messages a minute — all of that is handled in the notification service.