GrabNaveen Kumar Jakuva PremkumarProblem & solution
Highly concurrent in-memory counter in GoLang
Summary
An overloaded database faced heavy traffic from campaign usage tracking, motivating an in-memory counter rather than an immediate SQL-to-NoSQL migration. Because exact counts were not required, increments could be cached in the application server and flushed periodically to reduce database queries and CPU use. The implementation uses Go’s Sync.Map, with LoadOrStore and CompareAndSwap for concurrent increments, plus LoadAndDelete to atomically remove values for asynchronous persistence; the source notes a fresh-map swap as an alternative locking optimization. On an Apple M4 Pro, the 2,000-key benchmark reported 53 ns/op and 1 billion operations per 60 seconds, versus 160 ns/op and 466 million operations for a Mutex-protected map, but Sync.Map used 88 B/op and four allocations. In production, update queries fell from 140 QPS to 45 QPS, master CPU from 35% to 18%, and replica CPU from 19% to 12%.
Context
Campaign usage counts needed to track total and daily activity, but exact accuracy was not a top priority. Heavy traffic caused high database CPU utilisation, so reducing write traffic and database Queries Per Second became preferable to immediately migrating from SQL to NoSQL.
Approach / What changed
The counter increments values in application memory and periodically flushes them to persistent storage. The selected implementation uses Go’s Sync.Map with LoadOrStore and CompareAndSwap for concurrent updates, while LoadAndDelete atomically removes values for asynchronous database writes.
Takeaways
Sync.Map measured 53 ns/op and 1 billion operations per 60 seconds for 2,000 keys, compared with 160 ns/op and 466 million operations for a Mutex-protected map.
The Sync.Map benchmark used 88 B/op and four allocations, while the Mutex approach used 0 B/op and zero allocations.
Production results included a reduction in tracking updates from 140 QPS to 45 QPS, master database CPU from 35% to 18%, and replica CPU from 19% to 12%.
Source and freshness
- Source
- engineering.grab.com
- Published
- Added to Yomu
- Last updated
Summaries are generated from the original by a language model. Check the original before relying on it.
Keep reading
Related reading
The Good Stuff
Paid picks we use ourselves. Links carry a referral code — a subscription through one earns us a commission at no extra cost to you.
The best engineering reads, once a week
One useful email. Unsubscribe anytime.