Last active
June 29, 2023 15:40
-
-
Save khuezy/ce2a2fd6e6b3e6d435d2b45f00201d28 to your computer and use it in GitHub Desktop.
AWS Get Closest DynamoDB Region
This file contains 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
// DNS Stack | |
export function Dns({ stack, app }: StackContext) { | |
... | |
createLatencyRecords(stack, 'example.app', 'zone_id') | |
} | |
function createLatencyRecords(stack: Stack, domainName: string, hostedZoneId: string) { | |
// Create TXT Records with region names under record name: lbr.example.app | |
// This allows us to query `dns.resolveTxt('lbr.example.app')` to get the | |
// region w/ the lowest latency for DynamoDB to connect to. | |
REGIONS.map(region => { | |
const record = new CfnRecordSet(stack as any, `Latency ${region}`, { | |
setIdentifier: `lbr_${region}`, | |
name: `lbr.${domainName}`, | |
type: 'TXT', | |
hostedZoneId, | |
region, | |
ttl: '31540000', // 1 year in seconds | |
resourceRecords: [`"${region}"`] | |
}) | |
// This record is global across all stages, so don't delete when removing stack. | |
record.applyRemovalPolicy(RemovalPolicy.RETAIN) | |
}) | |
} |
This file contains 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
import dns from 'dns/promises' | |
export const DYNAMODB_REGIONS = ['us-east-1', 'us-west-2', 'eu-west-2'] as const | |
type REGION = typeof DYNAMODB_REGIONS[number] | |
/** | |
* Gets the closest DynamoDB region based on server location. | |
* The closest region is determined by a TXT record DNS lookup. | |
* The TXT record contains the region info. | |
* | |
* Currently, the DynamoDB regions are: | |
* main: us-east-1 | |
* replicas: us-west-2, eu-west-2 | |
* | |
* If a user triggers an edge function in us-west-1, this will return the closest region | |
* us-west-2. | |
* | |
* | |
* @returns region | |
*/ | |
export async function getClosestDynamoReplicaRegion(): Promise<string> { | |
let region = process.env.AWS_REGION as REGION | |
// The region is in one of the replica regions | |
if (DYNAMODB_REGIONS.includes(region)) { | |
return region | |
} | |
// Get the closest TXT value from DNS | |
try { | |
const r = await dns.resolveTxt('lbr.example.app') | |
region = r[0][0] as REGION | |
} catch (err) { | |
console.error('Failed to resolve TXT record', { | |
region, err | |
}) | |
region = 'us-east-1' | |
} | |
return region | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment