Implementing put
, get
, del
, ttl
operations all in sync.
To implement this in space efficient way, following is our table structure :
+------------+--------------+
| Field | Type |
+------------+--------------+
| key | varchar(255) |
| value | text |
| expired_at | datetime |
+------------+--------------+
Put Query:
REPLACE INTO kv_store VALUES (?,?,?)
Get Query:
SELECT value FROM kv_store WHERE `key` = ? AND expired_at > NOW()
Del Query:
UPDATE kv_store SET expired_at = '1970-01-01' WHERE `key` = ? AND expired_at > NOW()
TTL expiry Query:
DELETE FROM kv_store WHERE expired_at <= NOW() LIMIT 1000
We run a go-routine ttlCleanupRoutine
that cleans expired keys after every 2 minutes.