-
Notifications
You must be signed in to change notification settings - Fork 40
fix(prisma): add retry for Aurora Serverless v2 connection errors #121
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 4 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
68e1396
fix(prisma): add retry for Aurora Serverless v2 connection errors (#1…
konokenj f18481f
test: update CDK snapshots for connection option changes
konokenj c4b9d35
fix(prisma): add success log after retry recovery
konokenj 908ab82
fix(prisma): add pool_timeout=30 and retry on connection pool timeout
konokenj f085b39
Update cdk/lib/constructs/database.ts
konokenj 46e64ff
fix: remove unnecessary pool_timeout parameter
konokenj File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,12 +1,70 @@ | ||
| import { PrismaClient } from '@prisma/client'; | ||
| import { Prisma, PrismaClient } from '@prisma/client'; | ||
|
|
||
| // https://www.prisma.io/docs/guides/nextjs | ||
|
|
||
| const globalForPrisma = global as unknown as { | ||
| prisma: PrismaClient; | ||
| }; | ||
|
|
||
| console.log(process.env.DATABASE_URL); | ||
| export const prisma = globalForPrisma.prisma || new PrismaClient({ log: ['query', 'info', 'warn', 'error'] }); | ||
| // Determine if an error is a transient connection issue that may resolve on retry. | ||
| // Aurora Serverless v2 can drop connections due to idle_session_timeout (60s) or auto-pause, | ||
| // and resume takes approximately 15 seconds. | ||
| // https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora-serverless-v2-auto-pause.html | ||
| function isRetryableError(error: unknown): boolean { | ||
| if (!(error instanceof Error)) return false; | ||
| const code = (error as { code?: string }).code; | ||
| if ( | ||
| code === 'P2024' || // Connection pool timeout | ||
| code === 'P1001' || // Can't reach database server | ||
| code === 'P1017' // Server has closed the connection | ||
| ) { | ||
| return true; | ||
| } | ||
| const msg = error.message; | ||
| return ( | ||
| msg.includes('idle-session timeout') || | ||
| msg.includes('terminating connection') || | ||
| msg.includes('Connection terminated') || | ||
| msg.includes('Timed out fetching a new connection from the connection pool') || | ||
| msg.includes('ECONNRESET') | ||
| ); | ||
| } | ||
|
|
||
| const basePrisma = new PrismaClient(); | ||
|
|
||
| async function withRetry<T>(fn: () => Promise<T>, maxRetries = 3, baseDelay = 500): Promise<T> { | ||
| let lastError: unknown; | ||
| for (let attempt = 0; attempt <= maxRetries; attempt++) { | ||
| try { | ||
| const result = await fn(); | ||
| if (attempt > 0) { | ||
| console.warn(`Prisma query succeeded after ${attempt} retry(s)`); | ||
| } | ||
| return result; | ||
| } catch (error) { | ||
| lastError = error; | ||
| if (attempt === maxRetries || !isRetryableError(error)) throw error; | ||
| // Discard stale connections before retrying | ||
| await basePrisma.$disconnect(); | ||
| const delay = baseDelay * Math.pow(2, attempt) + Math.random() * 100; | ||
| console.warn(`Prisma retry attempt ${attempt + 1}/${maxRetries}, waiting ${Math.round(delay)}ms`); | ||
| await new Promise((r) => setTimeout(r, delay)); | ||
| } | ||
| } | ||
| throw lastError; | ||
| } | ||
|
|
||
| const retryExtension = Prisma.defineExtension({ | ||
| name: 'retry-on-connection-error', | ||
| query: { | ||
| $allModels: { | ||
| async $allOperations({ args, query }) { | ||
| return withRetry(() => query(args)); | ||
| }, | ||
| }, | ||
| }, | ||
| }); | ||
|
|
||
| export const prisma = basePrisma.$extends(retryExtension) as unknown as PrismaClient; | ||
|
|
||
| if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.