improvement(db): cut hot-path connector count and rate-limit lock costs by waleedlatif1 · Pull Request #8944 · simstudioai/sim · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
improvement(rate-limit): admit provider requests in one statement on …
…the database bucket

Lock, refill, decide and spend every dimension in a single CTE so a hot
bucket row stays locked for one statement plus the commit instead of a
round trip per dimension. The clock is read before the statement, matching
the Redis backend, so a contended admission never sees more tokens.
  • Loading branch information
waleedlatif1 committed Oct 12, 2026
commit fda1111ca263cb03b94c458b498db7dd15f919bf
16 changes: 11 additions & 5 deletions apps/sim/lib/core/rate-limiter/provider-admission.test.ts
35 changes: 0 additions & 35 deletions apps/sim/lib/core/rate-limiter/storage/db-token-bucket.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,41 +44,6 @@ describe('PostgreSQL token bucket', () => {
expect(dbChainMockFns.set).toHaveBeenCalledWith(expect.objectContaining({ tokens: '0' }))
})

it('initializes request and cooldown buckets in a consistent order without duplicate keys', async () => {
const now = new Date()
dbChainMockFns.limit.mockResolvedValue([
{ key: 'cooldown', tokens: '0', lastRefillAt: now, blockedUntil: null },
{ key: 'requests', tokens: '10', lastRefillAt: now, blockedUntil: null },
{ key: 'tokens', tokens: '10', lastRefillAt: now, blockedUntil: null },
])

expect(
await new DbTokenBucket().consumeTokensAtomically(
[
{ key: 'tokens', cost: 2, config: CONFIG },
{ key: 'requests', cost: 1, config: CONFIG },
],
{ cooldownKeys: ['cooldown', 'cooldown'], deadlineAt: now.getTime() + 1000 }
)
).toEqual({ allowed: true, retryAfterMs: 0 })

expect(dbChainMockFns.values).toHaveBeenCalledExactlyOnceWith([
{ key: 'cooldown', tokens: '0', lastRefillAt: now, updatedAt: now },
{ key: 'requests', tokens: '10', lastRefillAt: now, updatedAt: now },
{ key: 'tokens', tokens: '10', lastRefillAt: now, updatedAt: now },
])
expect(dbChainMockFns.set).toHaveBeenCalledWith({
tokens: '8',
lastRefillAt: now,
updatedAt: now,
})
expect(dbChainMockFns.set).toHaveBeenCalledWith({
tokens: '9',
lastRefillAt: now,
updatedAt: now,
})
})

it('accepts an empty reservation without attempting an empty insert', async () => {
dbChainMockFns.limit.mockResolvedValue([])

Expand Down
258 changes: 192 additions & 66 deletions apps/sim/lib/core/rate-limiter/storage/db-token-bucket.ts
Loading