3 pointsby ajithmanmu8 hours ago1 comment
  • ajithmanmu8 hours ago
    I built this to understand how billing platforms like Lago and Metronome work internally — not just calling Stripe's API, but building the metering and pricing layer.

    Most interesting parts:

    - Deduplication with Redis SET NX (atomic, no distributed locks)

    - Sliding window rate limiting with sorted sets (avoids fixed-window boundary problem)

    - Two-layer fraud detection: Z-score for volume spikes + cosine similarity on 24-dimensional hourly vectors for pattern anomalies. A stolen API key from a different timezone has normal volume but an inverted hourly pattern — Z-score misses it, cosine similarity drops to ~0.28

    - Tiered pricing in integer cents (never float math in billing)

    Runs locally with Docker Compose. Demo simulates 30 days of usage then injects fraud.

    Writeup: https://dev.to/ajithmanmu/i-built-a-usage-based-billing-engi...

    Happy to answer questions about any design decisions.