A Smaller Bedrock Gateway, Part 5: Gateway Stack: Inputs, Secrets, and the Data Tier
The gateway stack in readable YAML, part 1 of 3: parameters, generated secrets, PostgreSQL, and Valkey.
Series: A Smaller Bedrock Gateway (8 articles)
- …
- 5A Smaller Bedrock Gateway, Part 5: Gateway Stack: Inputs, Secrets, and the Data Tier This article
Last updated: 2026-11-13 (Fri) 18:22 GST
With the network deployed in Part 3 and the image built in Part 4, we can start the second stack. The gateway template is the larger of the two, so I will walk through it in three parts. This one covers what the stack needs from you, how it creates and protects its secrets, and the data tier: PostgreSQL for keys and spend, and Valkey for state the two replicas share.
The gateway template is published in fourteen blocks across Parts 5, 6, and 7. As before, save each block under the file name it gives. At the end of Part 7, one command joins them and checks the result.
What the stack needs from you
The parameters fall into four groups. The first wires the stack to its environment: the network stack name, the certificate, the two ingress ranges, the gateway's host name, and the image by digest. The second pins the model: the inference profile, the foundation model, and the alias clients use,
claude-sonnet-eu . The third sizes and protects the data tier. The defaults are PostgreSQL 16 on db.t4g.medium in Multi-AZ mode with 14 days of backups, Valkey 8.2 on cache.t4g.small with 7 days of snapshots, and deletion protection on for both the database and the load balancer. The last group controls operations: the two credential-slot switches used for rotation, the desired task count, which defaults to 0, log retention, and an optional SNS topic for alarms and an optional permissions boundary for the roles.Parameters
This block holds the template header, the metadata, and every parameter. Save this block as
gateway-01.yaml .AWSTemplateFormatVersion: '2010-09-09'
Description: >- Stack 2 of 2 for a private LiteLLM v1.109.1 gateway on Amazon ECS Fargate in eu-central-1. It imports stable VPC, subnet, security-group, hosted-zone, ALB log-bucket, and S3 prefix-list identities from stack 1. It creates an internal HTTPS Application Load Balancer, Multi-AZ PostgreSQL as the authoritative state store, and a private cluster-mode-disabled two-node Valkey 8.2 replication group for shared cross-replica coordination. Valkey uses TLS, RBAC, and KMS encryption from creation; LiteLLM response caching remains disabled. Generated A/B credentials support rotation without exposing secrets to migration. The service starts at zero tasks; orchestration must complete migration before increasing ServiceDesiredCount. This template creates no public route, transit gateway, VPN, or Route 53 Resolver inbound endpoint, and does not provision tokenisation, a vault, or request-level auditing.
Metadata: cfn-lint: config: # W6001 normally flags pass-through outputs. These outputs are the deliberate # final contract consumed by the migration runner, probe, and live validator. ignore_checks: - W6001
Parameters:
NetworkStackName: Type: String AllowedPattern: '^[A-Za-z][-A-Za-z0-9]{0,127}$' ConstraintDescription: Must be a valid CloudFormation stack name. Description: >- Name of the paired v2 network stack. Imports are limited to stable VPC, subnet, and security-group identities, HostedZoneId, the ALB access-log bucket name, and the Regional S3 prefix-list ID. The imported private subnets have no default route, so orchestration must verify that their endpoint policies and S3 gateway route support image pulls, secret injection, logs, and Bedrock before migration. For blue/green replacement, deploy new paired network and gateway stack names instead of changing imported identities on this retained-data stack.
CertificateArn: Type: String AllowedPattern: '^arn:aws[a-zA-Z-]*:acm:[a-z0-9-]+:[0-9]{12}:certificate\/[0-9A-Za-z-]+$' ConstraintDescription: Must be an ACM certificate ARN. Description: >- Regional ACM certificate covering the directly supplied GatewayDomainName.
ClientIngressCidr: Type: String AllowedPattern: '^(?:10\.(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\/(?:[89]|[12][0-9]|3[0-2])|172\.(?:1[6-9]|2[0-9]|3[01])\.(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\/(?:1[2-9]|2[0-9]|3[0-2])|192\.168\.(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\/(?:1[6-9]|2[0-9]|3[0-2]))$' ConstraintDescription: Must be an RFC 1918 IPv4 CIDR. Description: >- Private client source CIDR supplied by orchestration. It must match the client CIDR configured on the imported ALB security group.
AdminIngressCidr: Type: String AllowedPattern: '^(?:10\.(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\/(?:[89]|[12][0-9]|3[0-2])|172\.(?:1[6-9]|2[0-9]|3[01])\.(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\/(?:1[2-9]|2[0-9]|3[0-2])|192\.168\.(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\/(?:1[6-9]|2[0-9]|3[0-2]))$' ConstraintDescription: Must be an RFC 1918 IPv4 CIDR. Description: >- Separate private administrator source CIDR supplied by orchestration. It must match the administrator CIDR configured on the imported ALB security group and differ from ClientIngressCidr.
GatewayDomainName: Type: String MinLength: 11 MaxLength: 253 AllowedPattern: '^litellm\.(?=.{3,245}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$' ConstraintDescription: >- Must be a lowercase exact litellm.<DNS-zone> hostname without a wildcard or trailing dot. Description: >- Exact private gateway hostname supplied by orchestration. CloudFormation receives only the imported HostedZoneId and cannot prove DNS-name membership; orchestration must verify that this hostname belongs to that hosted zone and is covered by CertificateArn before deployment.
ModelId: Type: String AllowedValues: - eu.anthropic.claude-sonnet-4-6 Description: >- Exact eu-central-1 Bedrock Europe cross-Region inference profile ID supplied by orchestration.
FoundationModelId: Type: String AllowedValues: - anthropic.claude-sonnet-4-6 Description: >- Exact foundation-model ID supplied by orchestration for the six authorized Europe inference destination Regions.
ContainerImage: Type: String AllowedPattern: '^[0-9]{12}\.dkr\.ecr\.eu-central-1\.amazonaws\.com\/[a-z0-9](?:[a-z0-9._-]{0,254}[a-z0-9])?@sha256:[0-9a-f]{64}$' ConstraintDescription: >- Must be a standard ECR eu-central-1 digest URI with a single-segment repository name and lowercase sha256 digest. Tags, ECR FIPS endpoints, and public registries are rejected. Description: >- Digest-pinned hardened LiteLLM wrapper image built from Dockerfile.litellm-hardened and mirrored into this account in eu-central-1. CloudFormation parameter regex cannot compare the URI's 12-digit account to AWS::AccountId, so exact same-account repository IAM below is the enforcing boundary. The single-segment repository constraint supports that exact scope.
ModelAlias: Type: String Default: claude-sonnet-eu AllowedPattern: '^[A-Za-z0-9._/-]{1,128}$' Description: >- LiteLLM alias for the directly supplied ModelId. The probe consumes this value from the gateway stack output so runtime and validation cannot drift.
DbEngineMajorVersion: Type: String Default: '16' AllowedValues: - '16' - '17' Description: PostgreSQL major version. Minor patches remain automatic.
DbInstanceClass: Type: String Default: db.t4g.medium AllowedPattern: '^db\.[a-z0-9]+\.[a-z0-9]+$' Description: RDS for PostgreSQL instance class holding LiteLLM state.
DbMultiAZ: Type: String Default: 'true' AllowedValues: - 'true' - 'false' Description: Multi-AZ database deployment. Keep true for production.
EnableDatabaseDeletionProtection: Type: String Default: 'true' AllowedValues: - 'true' - 'false' Description: Database deletion protection. Keep true for production.
EnableAlbDeletionProtection: Type: String Default: 'true' AllowedValues: - 'true' - 'false' Description: Internal ALB deletion protection. Keep true for production.
DbBackupRetentionDays: Type: Number Default: 14 MinValue: 7 MaxValue: 35 Description: Automated database backup retention in days.
DatabaseCaCertificateIdentifier: Type: String Default: rds-ca-rsa2048-g1 AllowedValues: - rds-ca-rsa2048-g1 - rds-ca-rsa4096-g1 - rds-ca-ecc384-g1 Description: >- RDS server CA. Confirm that the selected CA is available in the deployment Region. Both ECS clients validate its chain and endpoint hostname.
ActiveAppCredentialSlot: Type: String Default: A AllowedValues: - A - B Description: >- Application credential slot injected into new runtime tasks. For rotation, update only the inactive secret, run the migration task, then switch this parameter and wait for the rolling ECS deployment before retiring the old slot.
ValkeyResourceId: Type: String MinLength: 1 MaxLength: 20 AllowedPattern: '^[a-z](?:[a-z0-9]|-(?=[a-z0-9])){0,19}$' ConstraintDescription: >- Must be 1-20 lowercase letters, digits, or nonconsecutive hyphens; start with a letter; and end with a letter or digit. Description: >- Required deployment-unique short ID used to derive the Valkey replication group, user, and user-group IDs. Choose a new value for blue/green replacement.
ValkeyEngineVersion: Type: String Default: '8.2' AllowedValues: - '8.2' Description: Fixed Valkey engine version reviewed for LiteLLM v1.109.1 coordination.
ValkeyNodeType: Type: String Default: cache.t4g.small AllowedValues: - cache.t4g.small Description: Fixed node type for the two-node coordination replication group.
ActiveValkeyCredentialSlot: Type: String Default: A AllowedValues: - A - B Description: >- Valkey password slot injected into newly started runtime tasks. Both slots support an operator-run overlapping password rotation without intentionally dropping existing connections. CloudFormation does not run or test this sequence.
ValkeyCredentialRevision: Type: String Default: '1' MaxLength: 9 AllowedPattern: '^[1-9][0-9]*$' ConstraintDescription: Must be a positive integer encoded as a string. Description: >- Increment after changing either Valkey secret. This changes the Valkey user and runtime task definition so CloudFormation re-resolves dynamic credentials.
ValkeySnapshotRetentionDays: Type: Number Default: 7 MinValue: 1 MaxValue: 35 Description: Daily Valkey snapshot retention in days.
ServiceDesiredCount: Type: Number Default: 0 AllowedValues: - 0 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10 - 11 - 12 - 13 - 14 - 15 - 16 - 17 - 18 - 19 - 20 Description: >- Runtime task count. Leave at zero for initial deployment. Direct CloudFormation deployment neither runs the one-shot migration task nor enforces its success. Orchestration must run the migration successfully and require exit code zero before setting this parameter to a nonzero value; use at least two for production.
LogRetentionDays: Type: Number Default: 365 AllowedValues: - 1 - 3 - 5 - 7 - 14 - 30 - 60 - 90 - 120 - 150 - 180 - 365 - 400 - 545 - 731 - 1096 - 1827 - 2192 - 2557 - 2922 - 3288 - 3653 Description: Finite retention for the KMS-encrypted ECS operational log group.
AlarmTopicArn: Type: String Default: '' AllowedPattern: '^$|^arn:aws[a-zA-Z-]*:sns:[a-z0-9-]+:[0-9]{12}:[A-Za-z0-9_+=,.@-]{1,256}$' ConstraintDescription: Must be empty or a valid SNS topic ARN. Description: Optional existing SNS topic for alarm and recovery notifications.
PermissionsBoundaryArn: Type: String Default: '' AllowedPattern: '^$|^arn:aws[a-zA-Z-]*:iam::[0-9]{12}:policy\/[A-Za-z0-9_+=,.@\/-]+$' ConstraintDescription: Must be empty or a valid IAM managed-policy ARN. Description: Optional permissions boundary applied to every IAM role in this stack.The rules repeat the network stack's guard rails, because this stack can be deployed on its own: Frankfurt only, the exact inference profile and foundation model, and distinct client and administrator ranges. The conditions turn the yes-or-no parameters into switches that the resources use.
Rules and conditions
This block holds the four rules and the conditions. Save this block as
gateway-02.yaml .Rules:
RequiredDeploymentRegion: Assertions: - Assert: Fn::Equals: - !Ref AWS::Region - eu-central-1 AssertDescription: This v2 gateway must be deployed in eu-central-1.
ExactInferenceProfile: Assertions: - Assert: Fn::Equals: - !Ref ModelId - eu.anthropic.claude-sonnet-4-6 AssertDescription: ModelId must be exactly eu.anthropic.claude-sonnet-4-6.
ExactFoundationModel: Assertions: - Assert: Fn::Equals: - !Ref FoundationModelId - anthropic.claude-sonnet-4-6 AssertDescription: FoundationModelId must be exactly anthropic.claude-sonnet-4-6.
DistinctIngressCidrs: Assertions: - Assert: Fn::Not: - Fn::Equals: - !Ref ClientIngressCidr - !Ref AdminIngressCidr AssertDescription: ClientIngressCidr and AdminIngressCidr must differ.
Conditions:
IsDbMultiAZ: !Equals [!Ref DbMultiAZ, 'true'] IsDatabaseDeletionProtected: !Equals [!Ref EnableDatabaseDeletionProtection, 'true'] IsAlbDeletionProtected: !Equals [!Ref EnableAlbDeletionProtection, 'true'] UseAppCredentialA: !Equals [!Ref ActiveAppCredentialSlot, A] UseValkeyCredentialA: !Equals [!Ref ActiveValkeyCredentialSlot, A] HasAlarmTopic: !Not [!Equals [!Ref AlarmTopicArn, '']] HasPermissionsBoundary: !Not [!Equals [!Ref PermissionsBoundaryArn, '']]Secrets the stack generates for you
You never type a password into this stack. A customer managed KMS key with rotation encrypts everything the gateway stores, and Secrets Manager generates six secrets: the LiteLLM administrator key, the LiteLLM salt key that encrypts values LiteLLM stores, two application database credentials, A and B, and two Valkey credentials, A and B. The paired slots are what make rotation without downtime possible, as Part 8 shows. Every secret and the key are retained when the stack is deleted, so you cannot lose access to encrypted data by accident.
Encryption key and generated secrets
This block starts the resources section. Save this block as
gateway-03.yaml .Resources:
# --------------------------------------------------------------------------- # Encryption and generated application secrets # ---------------------------------------------------------------------------
GatewayKmsKey: Type: AWS::KMS::Key DeletionPolicy: Retain UpdateReplacePolicy: Retain Properties: Description: >- LiteLLM secrets, PostgreSQL and Valkey storage, ECS and Valkey logs, database snapshots, and Performance Insights. EnableKeyRotation: true KeySpec: SYMMETRIC_DEFAULT KeyUsage: ENCRYPT_DECRYPT MultiRegion: false PendingWindowInDays: 30 KeyPolicy: Version: '2012-10-17' Statement: - Sid: EnableAccountAdministrationAndIamPolicies Effect: Allow Principal: AWS: !Sub 'arn:${AWS::Partition}:iam::${AWS::AccountId}:root' Action: 'kms:*' Resource: '*' - Sid: AllowCloudWatchLogsForSameAccountLogGroups Effect: Allow Principal: Service: !Sub 'logs.${AWS::Region}.${AWS::URLSuffix}' Action: - 'kms:Encrypt*' - 'kms:Decrypt*' - 'kms:ReEncrypt*' - 'kms:GenerateDataKey*' - 'kms:Describe*' Resource: '*' Condition: ArnLike: 'kms:EncryptionContext:aws:logs:arn': !Sub 'arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:*' Tags: - Key: Name Value: !Sub '${AWS::StackName}-litellm'
GatewayKmsKeyAlias: Type: AWS::KMS::Alias Properties: AliasName: !Sub 'alias/${AWS::StackName}-litellm-gateway' TargetKeyId: !Ref GatewayKmsKey
AdministratorKeySecret: Type: AWS::SecretsManager::Secret DeletionPolicy: Retain UpdateReplacePolicy: Retain Properties: Description: LiteLLM administrator bearer-key body. Never distribute it to clients. KmsKeyId: !Ref GatewayKmsKey GenerateSecretString: SecretStringTemplate: '{}' GenerateStringKey: administrator_key PasswordLength: 48 ExcludePunctuation: true Tags: - Key: Workload Value: litellm
SaltKeySecret: Type: AWS::SecretsManager::Secret DeletionPolicy: Retain UpdateReplacePolicy: Retain Properties: Description: >- Stable LiteLLM encryption salt. Do not rotate after encrypted credentials are stored. KmsKeyId: !Ref GatewayKmsKey GenerateSecretString: SecretStringTemplate: '{}' GenerateStringKey: salt_key PasswordLength: 48 ExcludePunctuation: true Tags: - Key: Workload Value: litellm
AppDbSecretA: Type: AWS::SecretsManager::Secret DeletionPolicy: Retain UpdateReplacePolicy: Retain Properties: Description: >- LiteLLM constrained runtime credential slot A. Rotate only while slot B is active. KmsKeyId: !Ref GatewayKmsKey GenerateSecretString: SecretStringTemplate: '{"username":"litellm_v2_app_a"}' GenerateStringKey: password PasswordLength: 40 ExcludePunctuation: true Tags: - Key: Workload Value: litellm - Key: CredentialSlot Value: A
AppDbSecretB: Type: AWS::SecretsManager::Secret DeletionPolicy: Retain UpdateReplacePolicy: Retain Properties: Description: >- LiteLLM constrained runtime credential slot B. Rotate only while slot A is active. KmsKeyId: !Ref GatewayKmsKey GenerateSecretString: SecretStringTemplate: '{"username":"litellm_v2_app_b"}' GenerateStringKey: password PasswordLength: 40 ExcludePunctuation: true Tags: - Key: Workload Value: litellm - Key: CredentialSlot Value: B
ValkeyCredentialSecretA: Type: AWS::SecretsManager::Secret DeletionPolicy: Retain UpdateReplacePolicy: Retain Properties: Description: >- LiteLLM Valkey password slot A for the deployment-unique Valkey user. Rotate only while slot B is active. KmsKeyId: !Ref GatewayKmsKey GenerateSecretString: SecretStringTemplate: !Sub '{"username":"article07-${ValkeyResourceId}"}' GenerateStringKey: password PasswordLength: 48 ExcludePunctuation: true IncludeSpace: false RequireEachIncludedType: true Tags: - Key: Workload Value: litellm - Key: CredentialStore Value: valkey - Key: CredentialSlot Value: A
ValkeyCredentialSecretB: Type: AWS::SecretsManager::Secret DeletionPolicy: Retain UpdateReplacePolicy: Retain Properties: Description: >- LiteLLM Valkey password slot B for the deployment-unique Valkey user. Rotate only while slot A is active. KmsKeyId: !Ref GatewayKmsKey GenerateSecretString: SecretStringTemplate: !Sub '{"username":"article07-${ValkeyResourceId}"}' GenerateStringKey: password PasswordLength: 48 ExcludePunctuation: true IncludeSpace: false RequireEachIncludedType: true Tags: - Key: Workload Value: litellm - Key: CredentialStore Value: valkey - Key: CredentialSlot Value: B
# --------------------------------------------------------------------------- # PostgreSQL remains the authoritative state store. Stack 1 owns the complete # security-group graph; stack 2 attaches imported database and cache SGs and # creates no SG rules. Valkey is only for shared runtime coordination. # ---------------------------------------------------------------------------PostgreSQL, the source of truth
LiteLLM keeps virtual keys, budgets, and recorded spend in PostgreSQL, so the database is the one component whose loss would matter. The instance is private, encrypted, Multi-AZ by default, and deletion-protected, and CloudFormation takes a final snapshot if the instance is ever deleted. RDS manages the administrator password itself. The parameter group forces TLS on every connection and keeps SQL statements out of the logs, so that keys and prompts never land there. Enhanced Monitoring and Performance Insights are on, with Performance Insights encrypted by the stack's key.
PostgreSQL
This block holds the parameter group, the subnet group, the monitoring role, and the database. Save this block as
gateway-04.yaml . DbParameterGroup: Type: AWS::RDS::DBParameterGroup Properties: Description: !Sub 'LiteLLM PostgreSQL ${DbEngineMajorVersion}; force TLS for every client.' Family: !Sub 'postgres${DbEngineMajorVersion}' Parameters: rds.force_ssl: '1' password_encryption: 'scram-sha-256' # pragma: allowlist secret # Password-changing DDL contains a SQL literal because PostgreSQL utility # statements cannot bind it. Keep statement text out of exported RDS logs. log_statement: none log_min_error_statement: panic Tags: - Key: Name Value: !Sub '${AWS::StackName}-force-tls'
DbSubnetGroup: Type: AWS::RDS::DBSubnetGroup Properties: DBSubnetGroupDescription: Imported private subnets for the LiteLLM database. SubnetIds: Fn::Split: - ',' - Fn::ImportValue: Fn::Sub: '${NetworkStackName}-PrivateSubnetIds' Tags: - Key: Name Value: !Sub '${AWS::StackName}-database'
RdsMonitoringRole: Type: AWS::IAM::Role Properties: PermissionsBoundary: !If - HasPermissionsBoundary - !Ref PermissionsBoundaryArn - !Ref 'AWS::NoValue' AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Sid: AllowRdsEnhancedMonitoring Effect: Allow Principal: Service: monitoring.rds.amazonaws.com Action: 'sts:AssumeRole' Condition: ArnLike: 'aws:SourceArn': !Sub 'arn:${AWS::Partition}:rds:${AWS::Region}:${AWS::AccountId}:db:*' StringEquals: 'aws:SourceAccount': !Ref AWS::AccountId ManagedPolicyArns: - !Sub 'arn:${AWS::Partition}:iam::aws:policy/service-role/AmazonRDSEnhancedMonitoringRole' Tags: - Key: Workload Value: litellm
Database: Type: AWS::RDS::DBInstance DeletionPolicy: Snapshot UpdateReplacePolicy: Snapshot Metadata: checkov: skip: - id: CKV_AWS_157 comment: >- MultiAZ is parameterized for disposable validation runs, but defaults to true and must remain true for production as documented by the parameter. Properties: Engine: postgres EngineVersion: !Ref DbEngineMajorVersion DBParameterGroupName: !Ref DbParameterGroup DBName: litellm_v2 DBInstanceClass: !Ref DbInstanceClass Port: 5432 AllocatedStorage: '100' MaxAllocatedStorage: 1000 StorageType: gp3 StorageEncrypted: true KmsKeyId: !GetAtt GatewayKmsKey.Arn PubliclyAccessible: false EnableIAMDatabaseAuthentication: true NetworkType: IPV4 MultiAZ: !If [IsDbMultiAZ, true, false] DeletionProtection: !If [IsDatabaseDeletionProtected, true, false] BackupRetentionPeriod: !Ref DbBackupRetentionDays DeleteAutomatedBackups: false CopyTagsToSnapshot: true AutoMinorVersionUpgrade: true AllowMajorVersionUpgrade: false CACertificateIdentifier: !Ref DatabaseCaCertificateIdentifier EnableCloudwatchLogsExports: - postgresql - upgrade MonitoringInterval: 60 MonitoringRoleArn: !GetAtt RdsMonitoringRole.Arn EnablePerformanceInsights: true PerformanceInsightsKMSKeyId: !GetAtt GatewayKmsKey.Arn PerformanceInsightsRetentionPeriod: 7 DBSubnetGroupName: !Ref DbSubnetGroup VPCSecurityGroups: - Fn::ImportValue: Fn::Sub: '${NetworkStackName}-DatabaseSecurityGroupId' MasterUsername: litellm_v2_admin ManageMasterUserPassword: true # pragma: allowlist secret MasterUserSecret: KmsKeyId: !GetAtt GatewayKmsKey.Arn Tags: - Key: Name Value: !Sub '${AWS::StackName}-litellm' - Key: Workload Value: litellm
# --------------------------------------------------------------------------- # Shared Valkey coordination. The paired network stack owns the private cache # security group and task-to-cache TCP/6379 path. This stack imports that SG, # uses only the primary endpoint, and never enables LiteLLM response caching. # ---------------------------------------------------------------------------Valkey, shared state for two replicas
Two replicas must agree on how much of a rate limit or budget each key has used, so they share that state through an ElastiCache for Valkey replication group instead of keeping private counters. Valkey is not a cache here: LiteLLM response caching stays off. The replication group has two nodes across Availability Zones with automatic failover, requires TLS, and encrypts data at rest. A deployment-unique Valkey user can run only the commands LiteLLM's coordination needs, and only on its own key prefix. If Valkey becomes unavailable, the gateway denies requests rather than admitting them unchecked.
Valkey
This block holds the parameter group, the subnet group, the user, the user group, and the replication group. Save this block as
gateway-05.yaml . ValkeyParameterGroup: Type: AWS::ElastiCache::ParameterGroup Properties: CacheParameterGroupFamily: valkey8 Description: LiteLLM coordination parameters for Valkey 8.x. Properties: maxmemory-policy: noeviction reserved-memory-percent: '25' Tags: - Key: Workload Value: litellm
ValkeySubnetGroup: Type: AWS::ElastiCache::SubnetGroup Properties: Description: Imported private subnets for the LiteLLM coordination store. SubnetIds: Fn::Split: - ',' - Fn::ImportValue: Fn::Sub: '${NetworkStackName}-PrivateSubnetIds' Tags: - Key: Workload Value: litellm
ValkeyUser: Type: AWS::ElastiCache::User Properties: Engine: valkey UserId: !Sub 'article07-${ValkeyResourceId}-proxy' UserName: !Sub 'article07-${ValkeyResourceId}' # Commands are the explicit LiteLLM v1.109.1 coordination union. Global # keyspace and administrative commands, including FLUSHALL, stay denied. AccessString: >- on ~article07:* &article07:* +ping +info +client|setinfo +get +mget +set +del +exists +incr +incrby +decrby +incrbyfloat +ttl +expire +pexpire +time +zadd +zcard +zrem +zremrangebyscore +eval +evalsha +script|load +publish +subscribe +rpush +ltrim +lpop +multi +exec AuthenticationMode: Type: password Passwords: - !Sub '{{resolve:secretsmanager:${ValkeyCredentialSecretA}:SecretString:password}}' - !Sub '{{resolve:secretsmanager:${ValkeyCredentialSecretB}:SecretString:password}}' Tags: # Changing this tag forces an AWS::ElastiCache::User update so both # password dynamic references are resolved again after a secret rotation. - Key: CredentialRevision Value: !Ref ValkeyCredentialRevision - Key: Workload Value: litellm
ValkeyUserGroup: Type: AWS::ElastiCache::UserGroup Properties: Engine: valkey UserGroupId: !Sub 'article07-${ValkeyResourceId}-group' # Valkey user groups do not require the permissive built-in default user. UserIds: - !Ref ValkeyUser Tags: - Key: Workload Value: litellm
ValkeyReplicationGroup: Type: AWS::ElastiCache::ReplicationGroup DeletionPolicy: Snapshot UpdateReplacePolicy: Snapshot Properties: ReplicationGroupId: !Sub 'article07-${ValkeyResourceId}' ReplicationGroupDescription: >- Private two-node Valkey replication group for LiteLLM shared coordination. Engine: valkey EngineVersion: !Ref ValkeyEngineVersion CacheNodeType: !Ref ValkeyNodeType CacheParameterGroupName: !Ref ValkeyParameterGroup CacheSubnetGroupName: !Ref ValkeySubnetGroup SecurityGroupIds: - Fn::ImportValue: Fn::Sub: '${NetworkStackName}-CacheSecurityGroupId' NetworkType: ipv4 Port: 6379 ClusterMode: disabled NumCacheClusters: 2 AutomaticFailoverEnabled: true MultiAZEnabled: true TransitEncryptionEnabled: true TransitEncryptionMode: required AtRestEncryptionEnabled: true KmsKeyId: !GetAtt GatewayKmsKey.Arn UserGroupIds: - !Ref ValkeyUserGroup SnapshotRetentionLimit: !Ref ValkeySnapshotRetentionDays AutoMinorVersionUpgrade: true LogDeliveryConfigurations: - DestinationDetails: CloudWatchLogsDetails: LogGroup: !Ref ValkeySlowLogGroup DestinationType: cloudwatch-logs LogFormat: json LogType: slow-log - DestinationDetails: CloudWatchLogsDetails: LogGroup: !Ref ValkeyEngineLogGroup DestinationType: cloudwatch-logs LogFormat: json LogType: engine-log Tags: - Key: Name Value: !Sub '${AWS::StackName}-valkey' - Key: Workload Value: litellm
# --------------------------------------------------------------------------- # Internal HTTPS ingress. The listener is deny-by-default, and the imported # ALB security group plus these path/source rules limit network reachability. # LiteLLM authentication remains mandatory. Clients outside this VPC need # private routing, return routes, and hybrid DNS forwarding that resolves # GatewayDomainName through the imported private hosted zone. This stack creates # no transit gateway, VPN, or Route 53 Resolver inbound endpoint. # ---------------------------------------------------------------------------A quick recap of activities
In this part, we saved the first third of the gateway template:
- Parameters for the environment, the model, the data tier, and operations, with the task count starting at 0.
- Rules that repeat the Region, model, and ingress-range guard rails.
- A KMS key and six generated secrets, with paired slots for rotation.
- A private, TLS-only, Multi-AZ PostgreSQL database that keeps statements out of its logs.
- A two-node, TLS-only Valkey replication group with a narrowly scoped user.
Conclusion
The gateway now has somewhere safe to keep its state. In Part 6, I will add the front door that clients connect to, and the IAM roles that decide what each task may do.
This is Part 5 of the eight-part A Smaller Bedrock Gateway series. Part 1 covers the design, Parts 2 and 3 the network stack, Part 4 the hardened image, Parts 5 to 7 the gateway stack, and Part 8 the deployment, validation, and day-two operations.
Series: A Smaller Bedrock Gateway (8 articles)
- …
- 5A Smaller Bedrock Gateway, Part 5: Gateway Stack: Inputs, Secrets, and the Data Tier This article
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article