Sobes.tech
Senior

Question about a slow service For example, when creating an order. There is a request to the service and a response, and between these two actions, we log the products ordered (for example, to count the popularity of products). The analytics service periodically works slowly or times out, and we fail to respond, losing orders. What to do to stop losing orders and money accordingly? Come up with a way to parallelize the order and analytics.

sobes.tech AI

Answer from AI

To avoid losing orders due to slow analytics, it is necessary to separate order processing from analytics and make them asynchronous.

Example solution:

  1. When creating an order, the service immediately responds to the client, confirming the order.
  2. Information about the order is sent to a message queue (e.g., Kafka, RabbitMQ).
  3. A separate service or worker reads messages from the queue and updates analytics.

This approach allows parallel processing and prevents blocking the main order flow due to slow analytics.

Example in Go using a channel to simulate a queue:

 type Order struct {
    ID    string
    Items []string
}

var analyticsChan = make(chan Order, 100)

func createOrder(order Order) {
    // Immediately confirm the order
    fmt.Println("Order created:", order.ID)
    // Send to analytics asynchronously
    go func() { analyticsChan <- order }()
}

func analyticsWorker() {
    for order := range analyticsChan {
        // Analytics processing
        fmt.Println("Processing analytics for order:", order.ID)
        time.Sleep(time.Second * 2) // simulate slow work
    }
}

func main() {
    go analyticsWorker()
    createOrder(Order{ID: "123", Items: []string{"item1", "item2"}})
    time.Sleep(time.Second * 5)
}

This approach increases fault tolerance and performance.

Question about a slow service For example, when… - sobes.tech