DEV Community

Ujjwal Dubey
Ujjwal Dubey

Posted on

Stop Your WhatsApp Assistant Quoting Yesterday's Stock: A TTL Cache Pattern for Small UAE Retailers

A customer asks "do you have this in size M?" on WhatsApp. The assistant says yes. The shop sold the last one at lunch. In a small Dubai boutique that is a refund conversation, not a sale.

I work at NxFlowAI, an AI automation agency that builds WhatsApp assistants for UAE retailers, serving UAE businesses remotely from Mumbai. This is the pattern we reach for when stock lives in a spreadsheet or a small POS export.

The problem

Reading the stock source on every message is slow and sometimes rate-limited. Caching it forever produces confident wrong answers. You need both speed and an honest answer about freshness.

Pattern: TTL cache plus a freshness rule

import time

class StockCache:
    def __init__(self, loader, ttl_seconds=600):
        self.loader = loader          # function returning {sku: qty}
        self.ttl = ttl_seconds
        self.data, self.loaded_at = {}, 0

    def get(self, sku):
        if time.time() - self.loaded_at > self.ttl:
            self.data = self.loader()
            self.loaded_at = time.time()
        return self.data.get(sku), time.time() - self.loaded_at

def answer(cache, sku):
    qty, age = cache.get(sku)
    if qty is None:
        return "handoff", "Let me ask the team about that item."
    if qty <= 2:
        return "handoff", "Stock is low on that one, a colleague will confirm in a moment."
    return "auto", "Yes, it is available. Want us to hold one?"
Enter fullscreen mode Exit fullscreen mode

Rules that matter more than the code

  1. Low stock always goes to a human. The cost of a wrong "yes" is higher than a short wait.
  2. Never promise a hold the system cannot create. If holds are manual, the reply says a colleague will confirm.
  3. Log the cache age with every answer. When a customer complains, you can see whether data was stale.
  4. Refresh after sales events. If the POS can send a webhook on sale, clear the cache instead of waiting for the TTL.

Choosing the TTL

Start with the slowest rate at which your stock really changes during busy hours, then shorten it if complaints appear. Write the number down with the reason, so the next developer does not guess.

If you want to compare this to buying a ready-made bot, our post on when a custom assistant beats a packaged chatbot covers the trade-offs.

Top comments (0)