Upsun User Documentation

Redis (Object cache)

Sign up

Get your free trial by clicking the link below.

Get your Upsun free trial

Redis is a multi-model database that allows you to store data in memory for high-performance data retrieval and key-value storage. Upsun supports two different Redis configurations:

  • Persistent: to set up fast persistent storage for your application
  • Ephemeral: to set up a non-persistent cache for your application

Supported versions Anchor to this heading

You can select the major and minor version.

Patch versions are applied periodically for bug fixes and the like. When you deploy your app, you always get the latest available patches.

  • 7.2
  • 7.0
  • 6.2

Deprecated versions Anchor to this heading

The following versions are deprecated. They’re available, but they aren’t receiving security updates from upstream and aren’t guaranteed to work. They’ll be removed in the future, so migrate to one of the supported versions.

  • 6.0
  • 5.0
  • 4.0
  • 3.2
  • 3.0
  • 2.8

Note that versions 3.0 and higher support up to 64 different databases per instance of the service, while Redis 2.8 only supports a single database.

Service types Anchor to this heading

Depending on your needs, you can set up Redis as persistent or ephemeral.

Relationship reference Anchor to this heading

For each service defined via a relationship to your application, Upsun automatically generates corresponding environment variables within your application container, in the $<RELATIONSHIP-NAME>_<SERVICE-PROPERTY> format.

Here is example information available through the service environment variables themselves, or through the PLATFORM_RELATIONSHIPS environment variable.

You can obtain the complete list of available service environment variables in your app container by running upsun ssh env.

Note that the information about the relationship can change when an app is redeployed or restarted or the relationship is changed. So your apps should only rely on the service environment variables directly rather than hard coding any values.

REDIS_USERNAME=
REDIS_SCHEME=redis
REDIS_SERVICE=redis
REDIS_FRAGMENT=
REDIS_IP=123.456.78.90
REDIS_EPOCH=0
REDIS_HOSTNAME=azertyuiopqsdfghjklm.redis.service._.eu-1.platformsh.site
REDIS_PORT=6379
REDIS_CLUSTER=azertyuiopqsdf-main-afdwftq
REDIS_HOST=rediscache.internal
REDIS_REL=redis
REDIS_PATH=
REDIS_QUERY={}
REDIS_PASSWORD=
REDIS_TYPE=redis:7.2
REDIS_PUBLIC=false
REDIS_HOST_MAPPED=false

For some advanced use cases, you can use the PLATFORM_RELATIONSHIPS environment variable. The structure of the PLATFORM_RELATIONSHIPS environment variable can be obtained by running upsun relationships in your terminal:

{
    "username": null,
    "scheme": "redis",
    "service": "redis",
    "fragment": null,
    "ip": "123.456.78.90",
    "hostname": "azertyuiopqsdfghjklm.redis.service._.eu-1.platformsh.site",
    "port": 6379,
    "cluster": "azertyuiopqsdf-main-7rqtwti",
    "host": "redis.internal",
    "rel": "redis",
    "path": null,
    "query": [],
    "password": null,
    "type": "redis:7.2",
    "public": false,
    "host_mapped": false
}

Here is an example of how to gather PLATFORM_RELATIONSHIPS environment variable information in a .environment file:

.environment
# Decode the built-in credentials object variable.
export RELATIONSHIPS_JSON=$(echo $PLATFORM_RELATIONSHIPS | base64 --decode)

# Set environment variables for individual credentials.
export APP_REDIS_HOST="$(echo $RELATIONSHIPS_JSON | jq -r '.redis[0].host')"

The format of the relationship is identical whether your Redis service is ephemeral or persistent.

Persistent Redis Anchor to this heading

By default, Redis is an ephemeral service that stores data in memory. This allows for fast data retrieval, but also means data can be lost when a container is moved or shut down.

To solve this issue, configure your Redis service as persistent. Persistent Redis stores data on a disk, restoring it if the container restarts.

To switch from persistent to ephemeral Redis, set up a new service with a different name.

Usage example Anchor to this heading

1. Configure the service Anchor to this heading

To define the service, use the redis-persistent endpoint:

.upsun/config.yaml
services:
    # The name of the service container. Must be unique within a project.
    <SERVICE_NAME>:
        type: redis-persistent:<VERSION>

Note that changing the name of the service replaces it with a brand new service and all existing data is lost. Back up your data before changing the service.

2. Add the relationship Anchor to this heading

To define the relationship, use the redis endpoint :

.upsun/config.yaml
applications:
    # The name of the app container. Must be unique within a project.
    <APP_NAME>:
        source:
            root: "myapp"
        
        [...]

        # Relationships enable access from this app to a given service.
        relationships:
            <SERVICE_NAME>:

services:
    # The name of the service container. Must be unique within a project.
    <SERVICE_NAME>:
        type: redis-persistent:<VERSION>

You can define <SERVICE_NAME> as you like, so long as it’s unique between all defined services and matches in both the application and services configuration.

The example above leverages default endpoint configuration for relationships. That is, it uses default endpoints behind-the-scenes, providing a relationship (the network address a service is accessible from) that is identical to the name of that service.

Depending on your needs, instead of default endpoint configuration, you can use explicit endpoint configuration.

With the above definition, the application container now has access to the service via the relationship <RELATIONSHIP_NAME> and its corresponding PLATFORM_RELATIONSHIPS environment variable.

For PHP, enable the extension for the service:

.upsun/config.yaml
applications:
    # The name of the app container. Must be unique within a project.
    <APP_NAME>:
        source:
            root: "myapp"
        
        [...]

        runtime:
            extensions:
                - redis

        # Relationships enable access from this app to a given service.
        relationships:
            <SERVICE_NAME>:

services:
    # The name of the service container. Must be unique within a project.
    <SERVICE_NAME>:
        type: redis-persistent:<VERSION>

Configuration example Anchor to this heading

Service and app configuration Anchor to this heading

.upsun/config.yaml
applications:
    # The name of the app container. Must be unique within a project.
    <APP_NAME>:
        source:
            root: "myapp"
        
        [...]

        # Relationships enable access from this app to a given service.
        relationships:
            redis:

services:
    # The name of the service container. Must be unique within a project.
    redis:
        type: redis-persistent:7.2

Use in app Anchor to this heading

To use the configured service in your app, add a configuration file similar to the following to your project.

.upsun/config.yaml
applications:
    # The name of the app container. Must be unique within a project.
    <APP_NAME>:
        source:
            root: "myapp"
        
        [...]

        # Relationships enable access from this app to a given service.
        relationships:
            redis:

services:
    # The name of the service container. Must be unique within a project.
    redis:
        type: redis-persistent:7.2

This configuration defines a single application (myapp), whose source code exists in the <PROJECT_ROOT>/myapp directory.
myapp has access to the redis service, via a relationship whose name is identical to the service name (as per default endpoint configuration for relationships).

From this, myapp can retrieve access credentials to the service through the relationship environment variables.

myapp/.environment
# Set environment variables for individual credentials.
# For more information, please visit https://docs.upsun.com/development/variables.html#service-environment-variables.
export CACHE_HOST="${REDIS_HOST}"
export CACHE_PORT="${REDIS_PORT}"
export CACHE_PASSWORD="${REDIS_PASSWORD}"
export CACHE_SCHEME="${REDIS_SCHEME}"

# Surface a Redis connection string for use in app.
export CACHE_URL="${CACHE_SCHEME}://${CACHE_PASSWORD}@${CACHE_HOST}:${CACHE_PORT}"

The above file β€” .environment in the myapp directory β€” is automatically sourced by Upsun into the runtime environment, so that the variable CACHE_URL can be used within the application to connect to the service.

Note that CACHE_URL, and all Upsun-service environment variables like REDIS_HOST, are environment-dependent. Unlike the build produced for a given commit, they can’t be reused across environments and only allow your app to connect to a single service instance on a single environment.

A file very similar to this is generated automatically for your when using the upsun ify command to migrate a codebase to Upsun.

Ephemeral Redis Anchor to this heading

By default, Redis is an ephemeral service that serves as a non-persistent cache. Ephemeral Redis stores data only in memory and requires no disk space. When the service reaches its memory limit, it triggers a cache cleanup. To customize those cache cleanups, set up an eviction policy.

Make sure your app doesn’t rely on ephemeral Redis for persistent storage as it can cause issues. For example, if a container is moved during region maintenance, the deploy and post_deploy hooks don’t run and an app that treats the cache as permanent shows errors.

To prevent data from getting lost when a container is moved or shut down, you can use the persistent Redis configuration. Persistent Redis provides a cache with persistent storage.

Usage example Anchor to this heading

1. Configure the service Anchor to this heading

To define the service, use the redis endpoint:

.upsun/config.yaml
services:
    # The name of the service container. Must be unique within a project.
    <SERVICE_NAME>:
        type: redis:<VERSION>

Note that changing the name of the service replaces it with a brand new service and all existing data is lost. Back up your data before changing the service.

2. Add the relationship Anchor to this heading

To define the relationship, use the redis endpoint :

.upsun/config.yaml
applications:
    # The name of the app container. Must be unique within a project.
    <APP_NAME>:
        source:
            root: "myapp"
        
        [...]

        # Relationships enable access from this app to a given service.
        relationships:
            <SERVICE_NAME>:

services:
    # The name of the service container. Must be unique within a project.
    <SERVICE_NAME>:
        type: redis:<VERSION>

You can define <SERVICE_NAME> as you like, so long as it’s unique between all defined services and matches in both the application and services configuration.

The example above leverages default endpoint configuration for relationships. That is, it uses default endpoints behind-the-scenes, providing a relationship (the network address a service is accessible from) that is identical to the name of that service.

Depending on your needs, instead of default endpoint configuration, you can use explicit endpoint configuration.

With the above definition, the application container now has access to the service via the relationship <RELATIONSHIP_NAME> and its corresponding PLATFORM_RELATIONSHIPS environment variable.

For PHP, enable the extension for the service:

.upsun/config.yaml
applications:
    # The name of the app container. Must be unique within a project.
    <APP_NAME>:
        source:
            root: "myapp"
        
        [...]

        runtime:
            extensions:
                - redis

        # Relationships enable access from this app to a given service.
        relationships:
            <SERVICE_NAME>:

services:
    # The name of the service container. Must be unique within a project.
    <SERVICE_NAME>:
        type: redis:<VERSION>

Configuration example Anchor to this heading

Service and app configuration Anchor to this heading

.upsun/config.yaml
applications:
    # The name of the app container. Must be unique within a project.
    <APP_NAME>:
        source:
            root: "myapp"
        
        [...]

        # Relationships enable access from this app to a given service.
        relationships:
            redis:

services:
    # The name of the service container. Must be unique within a project.
    redis:
        type: redis:7.2

Use in app Anchor to this heading

To use the configured service in your app, add a configuration file similar to the following to your project.

.upsun/config.yaml
applications:
    # The name of the app container. Must be unique within a project.
    <APP_NAME>:
        source:
            root: "myapp"
        
        [...]

        # Relationships enable access from this app to a given service.
        relationships:
            redis:

services:
    # The name of the service container. Must be unique within a project.
    redis:
        type: redis:7.2

This configuration defines a single application (myapp), whose source code exists in the <PROJECT_ROOT>/myapp directory.
myapp has access to the redis service, via a relationship whose name is identical to the service name (as per default endpoint configuration for relationships).

From this, myapp can retrieve access credentials to the service through the relationship environment variables.

myapp/.environment
# Set environment variables for individual credentials.
# For more information, please visit https://docs.upsun.com/development/variables.html#service-environment-variables.
export CACHE_HOST="${REDIS_HOST}"
export CACHE_PORT="${REDIS_PORT}"
export CACHE_PASSWORD="${REDIS_PASSWORD}"
export CACHE_SCHEME="${REDIS_SCHEME}"

# Surface a Redis connection string for use in app.
export CACHE_URL="${CACHE_SCHEME}://${CACHE_PASSWORD}@${CACHE_HOST}:${CACHE_PORT}"

The above file β€” .environment in the myapp directory β€” is automatically sourced by Upsun into the runtime environment, so that the variable CACHE_URL can be used within the application to connect to the service.

Note that CACHE_URL, and all Upsun-service environment variables like REDIS_HOST, are environment-dependent. Unlike the build produced for a given commit, they can’t be reused across environments and only allow your app to connect to a single service instance on a single environment.

A file very similar to this is generated automatically for your when using the upsun ify command to migrate a codebase to Upsun.

Multiple databases Anchor to this heading

Redis 3.0 and above support up to 64 databases. But you can’t set up different access rights to each database. When you set up a relationship connection, access to all of the databases is automatically granted.

The way to access a particular database depends on the client library you’re using:

Use the Redis select command:

<?php
$redis = new Redis();
$redis->connect(getenv('REDIS_HOST'), getenv('REDIS_PORT'));

$redis->select(0);       // switch to DB 0
$redis->set('x', '42');  // write 42 to x
$redis->move('x', 1);    // move to DB 1
$redis->select(1);       // switch to DB 1
$redis->get('x');        // returns 42

To manage thread safety, the Python library suggests using separate client instances for each database:

import os
from redis import Redis

database0 = Redis(host=os.getenv('REDIS_HOST'), port=os.getenv('REDIS_PORT'), db=0)
database1 = Redis(host=os.getenv('REDIS_HOST'), port=os.getenv('REDIS_PORT'), db=1)

Use the Redis select command:

const redis = require('redis');

const client = redis.createClient(process.env.REDIS_PORT, process.env.REDIS_HOST);

await client.SELECT(0);                  // switch to DB 0
await client.set('x', '42');             // write 42 to x
await client.MOVE('x', 1);               // move to DB 1
await client.SELECT(1);                  // switch to DB 1
const value = await client.get('x');     // returns 42

Eviction policy Anchor to this heading

When Redis reaches its memory limit, it triggers a cache cleanup. To customize those cache cleanups, set up an eviction policy such as the following:

.upsun/config.yaml
services:
    # The name of the service container. Must be unique within a project.
    redis:
        type: "redis:7.2"
        configuration:
            maxmemory_policy: allkeys-lfu

The following table presents the possible values:

Value Policy description
allkeys-lru Removes the oldest cache items first. This is the default policy when maxmemory_policy isn’t set.
noeviction New items aren’t saved when the memory limit is reached.
allkeys-lfu Removes least frequently used cache items first.
volatile-lru Removes least recently used cache items with the expire field set to true.
volatile-lfu Removes least frequently used cache items with the expire field set to true.
allkeys-random Randomly removes cache items to make room for new data.
volatile-random Randomly removes cache items with the expire field set to true.
volatile-ttl Removes cache items with the expire field set to true and the shortest remaining time-to -live value.

For more information on the different policies, see the official Redis documentation.

Access your Redis service Anchor to this heading

After you’ve configured your Redis service, you can access it using either the Upsun CLI or through the Redis CLI.

Upsun CLI Anchor to this heading

Unlike the Redis CLI, connecting via the Upsun CLI does not require additional authentication steps if you are already authenticated in your terminal.

Access your Redis service by running the command:

upsun redis

Redis CLI Anchor to this heading

Retrieve the hostname and port you can connect to through the PLATFORM_RELATIONSHIPS environment variable. To do so, run the upsun relationships command.

After you’ve retrieved the hostname and port, open an SSH session. To access your Redis service, run the following command:

redis-cli -h HOSTNAME -p PORT

If you have a Grid project, note that the CONFIG GET and CONFIG SET admin commands are restricted. To get the current configuration, run the following command:

redis-cli -h HOSTNAME -p PORT info

Use Redis as a handler for PHP sessions Anchor to this heading

A PHP session allows you to store different data for each user through a unique session ID. By default, PHP handles sessions using files. But you can use Redis as a session handler, which means Redis stores and retrieves the data saved into sessions.

To set up Redis as your session handler, add a configuration similar to the following:

.upsun/config.yaml
applications:
    # The name of the app container. Must be unique within a project.
    myapp:
        source:
            root: "myapp"

            type: "php:8.3"

            relationships:
                redissession:

            variables:
                php:
                    session.save_handler: redis
                    session.save_path: "tcp://$SESSIONSTORAGE_HOSTNAME:$SESSIONSTORAGE_PORT"

            web:
                locations:
                    '/':
                        root: 'web'
                        passthru: '/index.php'
                        
services:
    # The name of the service container. Must be unique within a project.
    redissession:
        type: "redis-persistent:7.2"

Is this page helpful?