Skip Navigation
Show nav
Dev Center
  • Get Started
  • Documentation
  • Changelog
  • Search
  • Get Started
    • Node.js
    • Ruby on Rails
    • Ruby
    • Python
    • Java
    • PHP
    • Go
    • Scala
    • Clojure
    • .NET
  • Documentation
  • Changelog
  • More
    Additional Resources
    • Home
    • Elements
    • Products
    • Pricing
    • Careers
    • Help
    • Status
    • Events
    • Podcasts
    • Compliance Center
    Heroku Blog

    Heroku Blog

    Find out what's new with Heroku on our blog.

    Visit Blog
  • Log inorSign up
View categories

Categories

  • Heroku Architecture
    • Compute (Dynos)
      • Dyno Management
      • Dyno Concepts
      • Dyno Behavior
      • Dyno Reference
      • Dyno Troubleshooting
    • Stacks (operating system images)
    • Networking & DNS
    • Platform Policies
    • Platform Principles
  • Developer Tools
    • Command Line
    • Heroku VS Code Extension
  • Deployment
    • Deploying with Git
    • Deploying with Docker
    • Deployment Integrations
  • Continuous Delivery & Integration (Heroku Flow)
    • Continuous Integration
  • Language Support
    • Node.js
      • Working with Node.js
      • Node.js Behavior in Heroku
      • Troubleshooting Node.js Apps
    • Ruby
      • Rails Support
      • Working with Bundler
      • Working with Ruby
      • Ruby Behavior in Heroku
      • Troubleshooting Ruby Apps
    • Python
      • Working with Python
      • Background Jobs in Python
      • Python Behavior in Heroku
      • Working with Django
    • Java
      • Java Behavior in Heroku
      • Working with Java
      • Working with Maven
      • Working with Spring Boot
      • Troubleshooting Java Apps
    • PHP
      • PHP Behavior in Heroku
      • Working with PHP
    • Go
      • Go Dependency Management
    • Scala
    • Clojure
    • .NET
      • Working with .NET
  • Databases & Data Management
    • Heroku Postgres
      • Postgres Basics
      • Postgres Getting Started
      • Postgres Performance
      • Postgres Data Transfer & Preservation
      • Postgres Availability
      • Postgres Special Topics
      • Migrating to Heroku Postgres
    • Heroku Key-Value Store
    • Apache Kafka on Heroku
    • Other Data Stores
  • AI
    • Working with AI
    • Heroku Inference
      • Inference API
      • Quick Start Guides
      • AI Models
      • Inference Essentials
    • Vector Database
    • Model Context Protocol
  • Monitoring & Metrics
    • Logging
  • App Performance
  • Add-ons
    • All Add-ons
  • Collaboration
  • Security
    • App Security
    • Identities & Authentication
      • Single Sign-on (SSO)
    • Private Spaces
      • Infrastructure Networking
    • Compliance
  • Heroku Enterprise
    • Enterprise Accounts
    • Enterprise Teams
    • Heroku Connect (Salesforce sync)
      • Heroku Connect Administration
      • Heroku Connect Reference
      • Heroku Connect Troubleshooting
  • Patterns & Best Practices
  • Extending Heroku
    • Platform API
    • App Webhooks
    • Heroku Labs
    • Building Add-ons
      • Add-on Development Tasks
      • Add-on APIs
      • Add-on Guidelines & Requirements
    • Building CLI Plugins
    • Developing Buildpacks
    • Dev Center
  • Accounts & Billing
  • Troubleshooting & Support
  • Integrating with Salesforce
  • Databases & Data Management
  • Heroku Key-Value Store
  • Connecting to Heroku Key-Value Store

Connecting to Heroku Key-Value Store

English — 日本語に切り替える

Last updated April 14, 2025

Table of Contents

  • Connection Permissions
  • External Connections
  • Connecting in Java
  • Connecting in Ruby
  • Connecting in Python
  • Connecting in Node.js
  • Connecting in PHP
  • Connecting in Go
  • Connecting in .NET

Heroku Key-Value Store (KVS) is accessible from any language with a Redis driver, including all languages and frameworks supported by Heroku. You can also access Heroku Key-Value Store hosted on the Mini or Premium plan from clients running in your own environment.

We deprecated the REDIS_TLS_URL andREDIS_TEMPORARY_URL` config vars in December 2024. All Key-Value Store connections require TLS with REDIS_URL.

Connection Permissions

All Heroku Key-Value Store users are granted access to all commands within Redis except CONFIG, SHUTDOWN, BGREWRITEAOF, BGSAVE, SAVE, MOVE, MODULE, MIGRATE, SLAVEOF, REPLICAOF, ACL and DEBUG.

External Connections

In addition to being available to the Heroku runtime, you can access Heroku Key-Value Store Mini and Premium plan instances from clients running on your local computer or elsewhere.

All Heroku Key-Value Store plans require TLS connections. You must configure your client to support TLS. This process can require updating and deploying your application before returning the app to normal operation.

To connect from an external system or client, retrieve the Redis connection string using either of the following methods:

  • Running the heroku redis:credentials CLI command (for more information, see redis:credentials)
  • Inspecting your app’s config vars by running the command heroku config:get REDIS_URL -a example-app.

As of December 2024, REDIS_URL is the only config var for TLS connections for all Heroku Key-Value Store plans.

 

Heroku Key-Value Store uses self-signed certificates, which can require you to configure the verify_mode SSL setting of your Redis client.

 

The REDIS_URL config var can change at any time. If you rely on the config var outside of your Heroku app and it changes, you must recopy the value.

Connecting in Java

If you’re using a Mini Heroku Key-Value Store add-on, use REDIS_TLS_URL instead of REDIS_URL to connect to your KVS add-on via a TLS connection. See this Help article for the changes you must make for REDIS_URL.

A variety of ways exist to connect to Heroku Key-Value Store but each depends on the Java framework in use. All methods of connecting use the REDIS_URL environment variable to determine connection information.

Spring Boot

Spring Boot’s support for Redis picks up all Redis configuration such as REDIS_URL automatically. Define a LettuceClientConfigurationBuilderCustomizer bean to disable TLS peer verification:

@Configuration
class AppConfig {

    @Bean
    public LettuceClientConfigurationBuilderCustomizer lettuceClientConfigurationBuilderCustomizer() {
        return clientConfigurationBuilder -> {
            if (clientConfigurationBuilder.build().isUseSsl()) {
                clientConfigurationBuilder.useSsl().disablePeerVerification();
            }
        };
    }
}

Lettuce

This snippet uses the REDIS_URL environment variable to create a connection to Redis via Lettuce. StatefulRedisConnection is thread-safe and can be safely used in a multithreaded environment:

 public static StatefulRedisConnection<String, String> connect() {
    RedisURI redisURI = RedisURI.create(System.getenv("REDIS_URL"));
    redisURI.setVerifyPeer(false);

    RedisClient redisClient = RedisClient.create(redisURI);
    return redisClient.connect();
}

Jedis

This snippet uses the REDIS_URL environment variable to create a URI. The new URI is used to create a connection to Redis via Jedis. In this example, we’re creating one connection to Redis:

private static Jedis getConnection() {
    try {
        TrustManager bogusTrustManager = new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        };

        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, new TrustManager[]{bogusTrustManager}, new java.security.SecureRandom());

        HostnameVerifier bogusHostnameVerifier = (hostname, session) -> true;

        return new Jedis(URI.create(System.getenv("REDIS_URL")),
                sslContext.getSocketFactory(),
                sslContext.getDefaultSSLParameters(),
                bogusHostnameVerifier);

    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        throw new RuntimeException("Cannot obtain Redis connection!", e);
    }
}

If you’re running Jedis in a multithreaded environment, such as a web server, don’t use the same Jedis instance to interact with Redis. Instead, create a Jedis Pool so that the application code can check out a Redis connection and return it to the pool when it’s done:

// The assumption with this method is that it's been called when the application
// is booting up so that a static pool has been created for all threads to use.
// e.g. pool = getPool()
public static JedisPool getPool() {
    try {
        TrustManager bogusTrustManager = new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        };

        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, new TrustManager[]{bogusTrustManager}, new java.security.SecureRandom());

        HostnameVerifier bogusHostnameVerifier = (hostname, session) -> true;

        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(10);
        poolConfig.setMaxIdle(5);
        poolConfig.setMinIdle(1);
        poolConfig.setTestOnBorrow(true);
        poolConfig.setTestOnReturn(true);
        poolConfig.setTestWhileIdle(true);

        return new JedisPool(poolConfig,
                URI.create(System.getenv("REDIS_URL")),
                sslContext.getSocketFactory(),
                sslContext.getDefaultSSLParameters(),
                bogusHostnameVerifier);

    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        throw new RuntimeException("Cannot obtain Redis connection!", e);
    }
}
// In your multithreaded code this is where you'd checkout a connection
// and then return it to the pool
try (Jedis jedis = pool.getResource()){
  jedis.set("foo", "bar");
}

Connecting in Ruby

To use Redis in your Ruby application, you must include the redis gem in your Gemfile:

gem 'redis'

Run bundle install to download and resolve all dependencies.

You must use redis gem 4.0.2 and up. You can’t use 4.0.1 or below to connect to Heroku Key-Value Store over SSL natively as they ignore OpenSSL::SSL::VERIFY_NONE as a verification mode.

Connecting in Rails

Create an initializer file named config/initializers/redis.rb containing:

$redis = Redis.new(url: ENV["REDIS_URL"], ssl_params: { verify_mode: OpenSSL::SSL::VERIFY_NONE })

Connecting from Sidekiq

Create an initializer file named config/initializers/sidekiq.rb containing:

Sidekiq.configure_server do |config|
  config.redis = {
    url: ENV["REDIS_URL"],
    ssl_params: { verify_mode: OpenSSL::SSL::VERIFY_NONE }
  }
end

Sidekiq.configure_client do |config|
  config.redis = {
      url: ENV["REDIS_URL"],
      ssl_params: { verify_mode: OpenSSL::SSL::VERIFY_NONE }
  }
end

Connecting in Python

To use Redis in Python your application, use the redis package:

$ pip install redis
$ pip freeze > requirements.txt

And use this package to connect to REDIS_URL in your code:

import os
import redis

r = redis.from_url(os.environ.get("REDIS_URL"))

To connect with TLS, configure ssl_cert_reqs to disable certificate validation:

import os
from urllib.parse import urlparse
import redis

url = urlparse(os.environ.get("REDIS_URL"))
r = redis.Redis(host=url.hostname, port=url.port, password=url.password, ssl=(url.scheme == "rediss"), ssl_cert_reqs=None)

Connecting in Django

To use Redis in your Django application, if you’re running a Django version earlier than 4.0, use django-redis.

If you’re running Django version 4.0 or later, you can use django-redis or the built-in Redis backend support introduced in Django 4.0.

Using django-redis

Install the django-redis module:

$ pip install django-redis
$ pip freeze > requirements.txt

In your settings.py, configure django_redis.cache.RedisCache as the BACKEND for your CACHES:

import os

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": os.environ.get('REDIS_URL'),
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    }
}

To connect with TLS, configure ssl_cert_reqs to disable certificate validation:

import os

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": os.environ.get('REDIS_URL'),
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "CONNECTION_POOL_KWARGS": {
                "ssl_cert_reqs": None
            },
        }
    }
}

Using the Built-in Redis Backend Support

Django’s built-in Redis backend support requires redis-py 3.0.0 or higher.

In your settings.py, configure django.core.cache.backends.redis.RedisCache as the BACKEND for your CACHES:

import os

CACHES = {
    "default": {
        "BACKEND": "django.core.cache.backends.redis.RedisCache",
        "LOCATION": os.environ.get('REDIS_URL')
    }
}

To connect with TLS, configure ssl_cert_reqs to disable certificate validation:

import os

CACHES = {
    "default": {
        "BACKEND": "django.core.cache.backends.redis.RedisCache",
        "LOCATION": os.environ.get('REDIS_URL'),
        "OPTIONS": {
                "ssl_cert_reqs": None
        }
    }
}

Connecting in Node.js

redis Module

Add the redis NPM module to your dependencies:

npm install redis

Use the module to connect to REDIS_URL:

const redis = require("redis");
const client = redis.createClient({url: process.env.REDIS_URL});

Additionally, you can configure redis to use TLS. If you’re on a Node.js Redis version 4.0.0 or later, connect to TLS with:

const redis = require("redis");

const redis_url = process.env.REDIS_URL;
const client = redis.createClient({
  url: redis_url,
  socket: {
    tls: (redis_url.match(/rediss:/) != null),
    rejectUnauthorized: false,
  }
});

If you’re on a Node.js Redis version 3.1.2 and earlier, connect to TLS with:

const redis = require("redis");

const client = redis.createClient({
  url: process.env.REDIS_URL,
  tls: {
    rejectUnauthorized: false
  }
});

ioredis Module

Add ioredis NPM module to your dependencies:

npm install ioredis

And use the module to connect to REDIS_URL:

const Redis = require("ioredis");
const client = new Redis(process.env.REDIS_URL);

If you want to set up the client with TLS, you can use the following:

const Redis = require("ioredis");

const client = new Redis(process.env.REDIS_URL, {
    tls: {
        rejectUnauthorized: false
    }
});

Connecting in PHP

Connecting with the Redis Extension

Add ext-redis to your requirements in composer.json:

"require": {
  …
  "ext-redis": "*",
  …
}

Connect to Redis after parsing the REDIS_URL config var from the environment:

$url = parse_url(getenv("REDIS_URL"));
$redis = new Redis();
$redis->connect("tls://".$url["host"], $url["port"], 0, NULL, 0, 0, [
  "auth" => $url["pass"],
  "stream" => ["verify_peer" => false, "verify_peer_name" => false],
]);

Connecting with Predis

Add the predis package to your requirements in composer.json:

"require": {
  ...
  "predis/predis": "^1.1",
  ...
}

Connect to Redis using the REDIS_URL config var from the environment:

$redis = new Predis\Client(getenv('REDIS_URL') . "?ssl[verify_peer_name]=0&ssl[verify_peer]=0");

Connecting in Go

Add the go-redis package in your application:

$ go get github.com/redis/go-redis/v9

Import the package:

import "github.com/redis/go-redis/v9"

Connect to Redis using the REDIS_URL configuration variable:

uri := os.Getenv("REDIS_URL")
opts, err := redis.ParseURL(uri)
if err != nil {
    // Handle error
}

if strings.HasPrefix(uri, "rediss") {
    opts.TLSConfig = &tls.Config{
        InsecureSkipVerify: true,
    }
}
rdb := redis.NewClient(opts)

Connecting in .NET

To connect your .NET application to Heroku Key-Value store, you must use a Redis client library, such as StackExchange.Redis.

StackExchange.Redis

Add the StackExchange.Redis NuGet package:

$ dotnet add package StackExchange.Redis

Connect using the REDIS_URL environment variable:

using StackExchange.Redis;
using System;

string redisUrl = Environment.GetEnvironmentVariable("REDIS_URL");
var uri = new Uri(redisUrl);
var userInfoParts = uri.UserInfo.Split(':');
if (userInfoParts.Length != 2)
{
    throw new InvalidOperationException("REDIS_URL is not in the expected format ('redis://user:password@host:port')");
}

var configurationOptions = new ConfigurationOptions
{
    EndPoints = { { uri.Host, uri.Port } },
    Password = userInfoParts[1],
    Ssl = true,
};
configurationOptions.CertificateValidation += (sender, cert, chain, errors) => true;
ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(configurationOptions);

This code retrieves the connection string from the REDIS_URL environment variable and parses it to extract the host, port, and password. Then it configures the StackExchange.Redis client to connect using SSL and skip certificate validation, which is necessary for Heroku Key-Value store.

The ConnectionMultiplexer instance is designed to be shared and reused throughout your application for optimal performance. For applications using dependency injection, it’s generally recommended to register the IConnectionMultiplexer interface as a singleton to ensure efficient connection reuse.

Keep reading

  • Heroku Key-Value Store

Feedback

Log in to submit feedback.

Upgrading a Heroku Key-Value Store Version Connecting to Heroku Key-Value Store in a Private or Shield Space via PrivateLink

Information & Support

  • Getting Started
  • Documentation
  • Changelog
  • Compliance Center
  • Training & Education
  • Blog
  • Support Channels
  • Status

Language Reference

  • Node.js
  • Ruby
  • Java
  • PHP
  • Python
  • Go
  • Scala
  • Clojure
  • .NET

Other Resources

  • Careers
  • Elements
  • Products
  • Pricing
  • RSS
    • Dev Center Articles
    • Dev Center Changelog
    • Heroku Blog
    • Heroku News Blog
    • Heroku Engineering Blog
  • Twitter
    • Dev Center Articles
    • Dev Center Changelog
    • Heroku
    • Heroku Status
  • Github
  • LinkedIn
  • © 2025 Salesforce, Inc. All rights reserved. Various trademarks held by their respective owners. Salesforce Tower, 415 Mission Street, 3rd Floor, San Francisco, CA 94105, United States
  • heroku.com
  • Legal
  • Terms of Service
  • Privacy Information
  • Responsible Disclosure
  • Trust
  • Contact
  • Cookie Preferences
  • Your Privacy Choices