Skip to content

Commit 35b1e19

Browse files
authored
feat: speedup payment method sync (#98)
1 parent 2579e12 commit 35b1e19

File tree

3 files changed

+79
-150
lines changed

3 files changed

+79
-150
lines changed

package-lock.json

Lines changed: 58 additions & 135 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
"@fastify/swagger-ui": "^1.10.1",
3333
"dotenv": "^16.3.1",
3434
"fastify": "^4.24.3",
35+
"p-limit": "^3.1.0",
3536
"pg": "^8.11.3",
3637
"pg-node-migrations": "0.0.8",
3738
"pino": "^8.16.1",

src/lib/sync.ts

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import { pg as sql } from 'yesql'
1515
import { upsertPaymentIntents } from './payment_intents'
1616
import { upsertPlans } from './plans'
1717
import { upsertSubscriptionSchedules } from './subscription_schedules'
18+
import pLimit from 'p-limit'
1819

1920
const config = getConfig()
2021

@@ -305,21 +306,25 @@ export async function syncPaymentMethods(syncParams?: SyncBackfillParams): Promi
305306

306307
let synced = 0
307308

308-
for (const customerId of customerIds) {
309-
const syncResult = await fetchAndUpsert(
310-
() =>
311-
// The type parameter is optional, types are wrong
312-
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
313-
// @ts-ignore
314-
stripe.paymentMethods.list({
315-
limit: 100,
316-
customer: customerId,
317-
}),
318-
(items) => upsertPaymentMethods(items, syncParams?.backfillRelatedEntities)
319-
)
320-
321-
synced += syncResult.synced
322-
}
309+
// 10 in parallel
310+
const limit = pLimit(10)
311+
312+
const syncs = customerIds.map((customerId) =>
313+
limit(async () => {
314+
const syncResult = await fetchAndUpsert(
315+
() =>
316+
stripe.paymentMethods.list({
317+
limit: 100,
318+
customer: customerId,
319+
}),
320+
(items) => upsertPaymentMethods(items, syncParams?.backfillRelatedEntities)
321+
)
322+
323+
synced += syncResult.synced
324+
})
325+
)
326+
327+
await Promise.all(syncs)
323328

324329
return { synced }
325330
}

0 commit comments

Comments
 (0)