Connecting to Heroku Key-Value Store
Last updated October 11, 2024
Table of Contents
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.
On September 30, 2024, we changed the REDIS_URL
config var to be the secure TLS connection URL for all mini
Heroku Key-Value Store add-on plans. See this Help article for more information on what config var changes you must make to your Redis configuration.
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.
For Premium, Private, and Shield plans, Heroku Key-Value Store version 6.0 and higher 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.
For Mini plans, using TLS is optional, but encouraged via using the REDIS_TLS_URL
config var. Mini plans will require TLS connections on December 2, 2024.
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
.
For production Heroku Key-Value Store plans, only REDIS_URL
is available. For Heroku Key-Value Store Mini plans, REDIS_URL
and REDIS_TLS_URL
are both available for non-TLS and TLS connections. If you’re on a Heroku Key-Value Store Mini plan, use REDIS_TLS_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
.
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
and REDIS_TLS_URL
config vars 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
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
.
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
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
.
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"))
If your Redis requires 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",
}
}
}
If your Redis requires 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')
}
}
If your Redis requires 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
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
.
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
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
.
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
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
.
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)