Skip to main content
net6.0

The CDK Construct Library for AWS::ElastiCache (Stability: Experimental)

Published
Oct 20, 2026
yesterday
Total Downloads
22.3K
22,316

Install

dotnet add package Amazon.CDK.AWS.ElastiCache.Alpha --version 2.274.0-alpha.0
ProductVersions
.NET
net6.0

README

ElastiCache CDK Construct Library


cdk-constructs: Experimental

The APIs of higher level constructs in this module are experimental and under active development. They are subject to non-backward compatible changes or removal in any future version. These are not subject to the Semantic Versioning model and breaking changes will be announced in the release notes. This means that while you may use them, you may need to update your source code when upgrading to a newer version of this package.


This module has constructs for Amazon ElastiCache.

  • The ServerlessCache construct facilitates the creation and management of serverless cache.
  • The User and UserGroup constructs facilitate the creation and management of users for the cache.

Serverless Cache

Amazon ElastiCache Serverless is a serverless option that automatically scales cache capacity based on application traffic patterns. You can create a serverless cache using the ServerlessCache construct:

var vpc = new Vpc(this, "VPC");

var cache = new ServerlessCache(this, "ServerlessCache", new ServerlessCacheProps {
    Vpc = vpc
});

Connecting to serverless cache

To control who can access the serverless cache by the security groups, use the .connections attribute.

The serverless cache has a default port 6379.

This example allows an EC2 instance to connect to the serverless cache:

ServerlessCache serverlessCache;
Instance instance;


// allow the EC2 instance to connect to serverless cache on default port 6379
serverlessCache.Connections.AllowDefaultPortFrom(instance);

Using a custom engine version

The named CacheEngine and UserEngine static members cover the versions available at the time of the most recent CDK release. If ElastiCache releases a new engine version before it is added as a named member, use the .of(...) factory to target it without waiting for a CDK update:

Vpc vpc;


new ServerlessCache(this, "ServerlessCache", new ServerlessCacheProps {
    // Use any engine/version combination supported by ElastiCache:
    Engine = CacheEngine.Of("valkey", "9"),
    Vpc = vpc
});

The same pattern applies to UserEngine.of(engineType) for users and user groups.

Cache usage limits

You can configure usage limits on both cache data storage and ECPU/second for your cache to control costs and ensure predictable performance.

Configuration options:

  • Maximum limits: Ensure your cache usage never exceeds the configured maximum
  • Minimum limits: Reserve a baseline level of resources for consistent performance
  • Both: Define a range where your cache usage will operate

For more infomation, see Setting scaling limits to manage costs.

Vpc vpc;


var serverlessCache = new ServerlessCache(this, "ServerlessCache", new ServerlessCacheProps {
    Engine = CacheEngine.VALKEY_LATEST,
    Vpc = vpc,
    CacheUsageLimits = new CacheUsageLimitsProperty {
        // cache data storage limits (GB)
        DataStorageMinimumSize = Size.Gibibytes(2),  // minimum: 1GB
        DataStorageMaximumSize = Size.Gibibytes(3),  // maximum: 5000GB
        // rate limits (ECPU/second)
        RequestRateLimitMinimum = 1000,  // minimum: 1000
        RequestRateLimitMaximum = 10000
    }
});

Backups and restore

You can enable automatic backups for serverless cache. When automatic backups are enabled, ElastiCache creates a backup of the cache on a daily basis.

Also you can set the backup window for any time when it's most convenient. If you don't specify a backup window, ElastiCache assigns one automatically.

For more information, see Scheduling automatic backups.

To enable automatic backups, set the backupRetentionLimit property. You can also specify the snapshot creation time by setting backupTime property:

Vpc vpc;


var serverlessCache = new ServerlessCache(this, "ServerlessCache", new ServerlessCacheProps {
    Backup = new BackupSettings {
        // enable automatic backups and set the retention period to 6 days
        BackupRetentionLimit = 6,
        // set the backup window to 9:00 AM UTC
        BackupTime = Schedule.Cron(new CronOptions {
            Hour = "9",
            Minute = "0"
        })
    },
    Vpc = vpc
});

You can create a final backup by setting backupNameBeforeDeletion property.

Vpc vpc;


var serverlessCache = new ServerlessCache(this, "ServerlessCache", new ServerlessCacheProps {
    Engine = CacheEngine.VALKEY_LATEST,
    Backup = new BackupSettings {
        // set a backup name before deleting a cache
        BackupNameBeforeDeletion = "my-final-backup-name"
    },
    Vpc = vpc
});

You can restore from backups by setting snapshot ARNs to backupArnsToRestore property:

Vpc vpc;


var serverlessCache = new ServerlessCache(this, "ServerlessCache", new ServerlessCacheProps {
    Engine = CacheEngine.VALKEY_LATEST,
    Backup = new BackupSettings {
        // set the backup(s) to restore
        BackupArnsToRestore = new [] { "arn:aws:elasticache:us-east-1:123456789012:serverlesscachesnapshot:my-final-backup-name" }
    },
    Vpc = vpc
});

Encryption at rest

At-rest encryption is always enabled for Serverless Cache. There are two encryption options:

  • Default: When no kmsKey is specified (left as undefined), AWS owned KMS keys are used automatically
  • Customer Managed Key: Create a KMS key first, then pass it to the cache via the kmsKey property

Customer Managed Key for encryption at rest

ElastiCache supports symmetric Customer Managed key (CMK) for encryption at rest.

For more information, see Using customer managed keys from AWS KMS.

To use CMK, set your CMK to the kmsKey property:

using Amazon.CDK.AWS.KMS;

Key kmsKey;
Vpc vpc;


var serverlessCache = new ServerlessCache(this, "ServerlessCache", new ServerlessCacheProps {
    Engine = CacheEngine.VALKEY_LATEST,
    ServerlessCacheName = "my-serverless-cache",
    Vpc = vpc,
    // set Customer Managed Key
    KmsKey = kmsKey
});

Metrics and monitoring

You can monitor your serverless cache using CloudWatch Metrics via the metric method.

For more information about serverless cache metrics, see Serverless metrics and events for Valkey and Redis OSS and Serverless metrics and events for Memcached.

ServerlessCache serverlessCache;


// The 5 minutes average of the total number of successful read-only key lookups in the cache.
var cacheHits = serverlessCache.MetricCacheHitCount();

// The 5 minutes average of the total number of bytes used by the data stored in the cache.
var bytesUsedForCache = serverlessCache.MetricDataStored();

// The 5 minutes average of the total number of ElastiCacheProcessingUnits (ECPUs) consumed by the requests executed on the cache.
var elastiCacheProcessingUnits = serverlessCache.MetricProcessingUnitsConsumed();

// Create an alarm for ECPUs.
elastiCacheProcessingUnits.CreateAlarm(this, "ElastiCacheProcessingUnitsAlarm", new CreateAlarmOptions {
    Threshold = 50,
    EvaluationPeriods = 1
});

Import an existing serverless cache

To import an existing ServerlessCache, use the ServerlessCache.fromServerlessCacheAttributes method:

SecurityGroup securityGroup;


var importedServerlessCache = ServerlessCache.FromServerlessCacheAttributes(this, "ImportedServerlessCache", new ServerlessCacheAttributes {
    ServerlessCacheName = "my-serverless-cache",
    SecurityGroups = new [] { securityGroup }
});

User and User Group

Setup required properties and create:

var newDefaultUser = new NoPasswordUser(this, "NoPasswordUser", new NoPasswordUserProps {
    UserId = "default",
    AccessControl = AccessControl.FromAccessString("on ~* +@all")
});

var userGroup = new UserGroup(this, "UserGroup", new UserGroupProps {
    Users = new [] { newDefaultUser }
});

RBAC

In Valkey 7.2 and onward and Redis OSS 6.0 onward you can use a feature called Role-Based Access Control (RBAC). RBAC is also the only way to control access to serverless caches.

RBAC enables you to control cache access through user groups. These user groups are designed as a way to organize access to caches.

For more information, see Role-Based Access Control (RBAC).

To enable RBAC for ElastiCache with Valkey or Redis OSS, you take the following steps:

  • Create users.
  • Create a user group and add users to the user group.
  • Assign the user group to a cache.

Create users

First, you need to create users by using IamUser, PasswordUser or NoPasswordUser construct.

With RBAC, you create users and assign them specific permissions by using accessString property.

For more information, see Specifying Permissions Using an Access String.

You can create an IAM-enabled user by using IamUser construct:

var user = new IamUser(this, "User", new IamUserProps {
    // set user engine
    Engine = UserEngine.REDIS,

    // set user id
    UserId = "my-user",

    // set username
    UserName = "my-user",

    // set access string
    AccessControl = AccessControl.FromAccessString("on ~* +@all")
});

NOTE: IAM-enabled users must have matching user id and username. For more information, see Limitations. The construct can set automatically the username to be the same as the user id.

If you want to create a password authenticated user, use PasswordUser construct:

var user = new PasswordUser(this, "User", new PasswordUserProps {
    // set user engine
    Engine = UserEngine.VALKEY,

    // set user id
    UserId = "my-user-id",

    // set access string
    AccessControl = AccessControl.FromAccessString("on ~* +@all"),

    // set username
    UserName = "my-user-name",

    // set up to two passwords
    Passwords = new [] { SecretValue.SecretsManager("SecretIdForPassword"), SecretValue.SecretsManager("AnotherSecretIdForPassword") }
});

You can also create a no password required user by using NoPasswordUser construct:

var user = new NoPasswordUser(this, "User", new NoPasswordUserProps {
    // set user engine
    Engine = UserEngine.REDIS,

    // set user id
    UserId = "my-user-id",

    // set access string
    AccessControl = AccessControl.FromAccessString("on ~* +@all"),

    // set username
    UserName = "my-user-name"
});

NOTE: NoPasswordUser is only available for Redis Cache.

Default user

ElastiCache automatically creates a default user with both a user ID and username set to default. This default user cannot be modified or deleted. The user is created as a no password authentication user.

This user is intended for compatibility with the default behavior of previous Redis OSS versions and has an access string that permits it to call all commands and access all keys.

To use this automatically created default user in CDK, you can import it using NoPasswordUser.fromUserAttributes method. For more information on import methods, see the Import an existing user and user group section.

To add proper access control to a cache, replace the default user with a new one that is either disabled by setting the accessString to off -@all or secured with a strong password.

To change the default user, create a new default user with the username set to default. You can then swap it with the original default user.

For more information, see Applying RBAC to a Cache for ElastiCache with Valkey or Redis OSS.

If you want to create a new default user, userName must be default and userId must not be default by using NoPasswordUser or PasswordUser:

// use the original `default` user by using import method
var defaultUser = NoPasswordUser.FromUserAttributes(this, "DefaultUser", new UserBaseAttributes {
    // userId and userName must be 'default'
    UserId = "default"
});

// create a new default user
var newDefaultUser = new NoPasswordUser(this, "NewDefaultUser", new NoPasswordUserProps {
    // new default user id must not be 'default'
    UserId = "new-default",
    // new default username must be 'default'
    UserName = "default",
    // set access string
    AccessControl = AccessControl.FromAccessString("on ~* +@all")
});

NOTE: You can't create a new default user using IamUser because an IAM-enabled user's username and user ID cannot be different.

Add users to the user group

Next, use the UserGroup construct to create a user group and add users to it. Ensure that you include either the original default user or a new default user:

IUser newDefaultUser;
IUser user;
IUser anotherUser;


var userGroup = new UserGroup(this, "UserGroup", new UserGroupProps {
    // add users including default user
    Users = new [] { newDefaultUser, user }
});

// you can also add a user by using addUser method
userGroup.AddUser(anotherUser);

Assign user group

Finally, assign a user group to cache:

Vpc vpc;
UserGroup userGroup;


var serverlessCache = new ServerlessCache(this, "ServerlessCache", new ServerlessCacheProps {
    Engine = CacheEngine.VALKEY_LATEST,
    ServerlessCacheName = "my-serverless-cache",
    Vpc = vpc,
    // assign User Group
    UserGroup = userGroup
});

Grant permissions to IAM-enabled users

If you create IAM-enabled users, "elasticache:Connect" action must be allowed for the users and cache.

NOTE: You don't need grant permissions to no password required users or password authentication users.

For more information, see Authenticating with IAM.

To grant permissions, you can use the grantConnect method in IamUser and ServerlessCache constructs:

IamUser user;
ServerlessCache serverlessCache;
Role role;


// grant "elasticache:Connect" action permissions to role
user.GrantConnect(role);
serverlessCache.Grants.Connect(role);

Import an existing user and user group

You can import an existing user and user group by using import methods:

var stack = new Stack();

var importedIamUser = IamUser.FromUserId(this, "ImportedIamUser", "my-iam-user-id");

var importedPasswordUser = PasswordUser.FromUserAttributes(stack, "ImportedPasswordUser", new UserBaseAttributes {
    UserId = "my-password-user-id"
});

var importedNoPasswordUser = NoPasswordUser.FromUserAttributes(stack, "ImportedNoPasswordUser", new UserBaseAttributes {
    UserId = "my-no-password-user-id"
});

var importedUserGroup = UserGroup.FromUserGroupAttributes(this, "ImportedUserGroup", new UserGroupAttributes {
    UserGroupName = "my-user-group-name"
});

Changes from Previous Version

No structural changes between v2.273.0-alpha.0 and v2.274.0-alpha.0.

Adoption Assessment

A verified publisher signal is available. Assess fit from the package's supported frameworks, license and dependency graph rather than popularity alone.

This version is marked prerelease. Validate its API and upgrade path before production use.Compatibility metadata lists 1 target framework; confirm the exact target used by your application.

Related Guides & Workflows

Learn how to evaluate, integrate, or audit this package in your .NET project.