Ova

How to use Redis on Heroku?

Published in Cloud Services 8 mins read

Using Redis on Heroku allows your applications to leverage a fast, in-memory data store for caching, session management, job queues, and more, significantly enhancing performance and responsiveness. The primary way to integrate Redis with your Heroku application is either through Heroku's own Redis add-on or by connecting to an external Redis service like Redis Cloud.

Integrating Redis on Heroku: Two Primary Approaches

There are generally two main methods to use Redis with your Heroku application, each offering specific advantages.

Method 1: Using an External Redis Service (e.g., Redis Cloud)

This method involves provisioning a Redis instance with a third-party provider and then connecting your Heroku application to it. This can offer more control, advanced features, or specific compliance requirements.

Step-by-Step Guide for Redis Cloud Integration

Integrating Redis Cloud with your Heroku application follows a straightforward process to ensure your application can effectively utilize the external Redis instance.

1. Prepare Your Accounts

Before you begin, ensure you have the necessary accounts set up:

  • Create a Heroku account: If you don't have one, sign up at Heroku.
  • Create a Redis Cloud account: Register for a free or paid plan at Redis Cloud.
2. Set Up Heroku CLI

The Heroku Command Line Interface (CLI) is essential for interacting with your Heroku applications from your local development environment.

  • Install Heroku CLI: Download and install the CLI on your system from the Heroku Dev Center.
  • Log in to Heroku: Open your terminal or command prompt and log in to your Heroku account:
    heroku login

    Follow the prompts to complete the login process.

3. Provision Redis Cloud Instance

Once your Redis Cloud account is ready, you'll need to create a Redis database instance.

  • Create a new Redis instance: Within your Redis Cloud account dashboard, create a new subscription and then provision a new Redis database.
  • Obtain connection details: After creation, Redis Cloud will provide you with connection details, including the host, port, and most importantly, a connection URL (often prefixed with redis:// or rediss:// for TLS/SSL connections). This URL encapsulates all the necessary information for your application to connect.
4. Connect Your Heroku Application

The connection URL obtained from Redis Cloud must be made available to your Heroku application as an environment variable.

  • Set the environment variable: Use the Heroku CLI to set the REDIS_URL environment variable for your application:
    heroku config:set REDIS_URL="redis://your-redis-cloud-host:port" -a your-app-name

    Replace "redis://your-redis-cloud-host:port" with your actual Redis Cloud connection URL and your-app-name with the name of your Heroku application. This variable will be automatically injected into your application's environment.

5. Prepare and Deploy Your Code

Your application code needs to be configured to read this environment variable and establish a connection to Redis.

  • Configure your application code: Ensure your application's Redis client library is configured to read the REDIS_URL environment variable (e.g., process.env.REDIS_URL in Node.js, ENV['REDIS_URL'] in Ruby, or os.environ.get('REDIS_URL') in Python).
  • Commit your changes to Git: Save your code changes, especially any modifications to read the REDIS_URL.
    git add .
    git commit -m "Configure Redis Cloud connection"
  • Push your code to Heroku: Deploy your application with the updated code:
    git push heroku main
6. Access and Verify

After successful deployment, test your application to ensure Redis is functioning as expected.

  • Access your deployed Heroku application: Open your application in a web browser or use the Heroku CLI:
    heroku open -a your-app-name
  • Confirm Redis functionality: Interact with features in your application that rely on Redis (e.g., user sessions, cached data) to verify that the connection is active and data is being stored/retrieved correctly.

Method 2: Using the Heroku Redis Add-on

Heroku provides its own fully managed Redis service as an add-on, which is often the simplest way to get started.

  • Provision the add-on: From your terminal, navigate to your application's directory and create a Heroku Redis add-on instance:
    heroku addons:create heroku-redis:hobby-dev -a your-app-name

    Replace hobby-dev with your desired plan (e.g., premium-0, standard-0) and your-app-name with your Heroku application's name.

  • Automatic configuration: Heroku automatically sets a REDIS_URL environment variable for your application with the connection details. No manual configuration of the URL is needed on Heroku's side.
  • Check environment variables: You can verify the REDIS_URL is set:
    heroku config -a your-app-name

Connecting Your Application Code to Redis

Regardless of whether you use an external service or the Heroku add-on, your application code needs to connect to Redis using the REDIS_URL environment variable.

Example Code Snippets

Here are examples for common programming languages:

Python (using redis-py)

import os
import redis

# Get the Redis URL from environment variables
redis_url = os.environ.get('REDIS_URL')

if redis_url:
    # Connect to Redis
    r = redis.from_url(redis_url)
    print("Connected to Redis!")
    # Example usage: set and get a value
    r.set('mykey', 'Hello from Heroku Redis!')
    value = r.get('mykey')
    print(f"Value from Redis: {value.decode('utf-8')}")
else:
    print("REDIS_URL environment variable not set.")

Node.js (using ioredis or node-redis)

const Redis = require('ioredis');

// Get the Redis URL from environment variables
const redisUrl = process.env.REDIS_URL;

if (redisUrl) {
    // Connect to Redis
    const redis = new Redis(redisUrl);

    redis.on('connect', () => {
        console.log('Connected to Redis!');
        // Example usage: set and get a value
        redis.set('mykey', 'Hello from Heroku Redis!')
            .then(() => redis.get('mykey'))
            .then(value => {
                console.log(`Value from Redis: ${value}`);
                redis.quit(); // Disconnect
            })
            .catch(err => console.error('Redis error:', err));
    });

    redis.on('error', (err) => {
        console.error('Redis connection error:', err);
    });
} else {
    console.log("REDIS_URL environment variable not set.");
}

Ruby (using redis gem)

require 'redis'

# Get the Redis URL from environment variables
redis_url = ENV['REDIS_URL']

if redis_url
  # Connect to Redis
  redis = Redis.new(url: redis_url)
  puts "Connected to Redis!"
  # Example usage: set and get a value
  redis.set('mykey', 'Hello from Heroku Redis!')
  value = redis.get('mykey')
  puts "Value from Redis: #{value}"
  redis.quit # Disconnect
else
  puts "REDIS_URL environment variable not set."
end

Best Practices for Redis on Heroku

To ensure optimal performance and reliability, consider these best practices when using Redis with your Heroku application.

Choosing the Right Plan

  • Start small: For development and testing, a free or hobby-tier plan (like Heroku Redis hobby-dev or Redis Cloud's free tier) is sufficient.
  • Scale with demand: As your application grows, monitor Redis usage (memory, connections, operations per second) and upgrade to a higher-tier plan that offers more memory, dedicated resources, and better performance guarantees.

Data Persistence and Backup

  • Understand persistence: Redis is an in-memory data store, but it can be configured for persistence (RDB snapshots, AOF log). Heroku Redis add-ons and Redis Cloud typically manage this for you, but understand the implications for data recovery.
  • Backups: Ensure your chosen Redis service has robust backup and restore capabilities. For critical data, consider separate database solutions alongside Redis for primary storage.

Security Considerations

  • Environment variables: Never hardcode Redis credentials directly into your application code. Always use environment variables (REDIS_URL).
  • TLS/SSL: If available, use rediss:// (secure Redis) for connections to encrypt data in transit, especially for external Redis services. Heroku Redis add-ons often handle TLS automatically.
  • Access control: Utilize any IP whitelisting or password protection features offered by your Redis provider.

Monitoring and Performance

  • Heroku Metrics: For Heroku Redis, use Heroku's built-in metrics and logging to monitor memory usage, connections, and throughput.
  • Redis Cloud Dashboard: If using Redis Cloud, their dashboard provides detailed metrics and insights into your Redis instance's performance.
  • Application-level monitoring: Instrument your application code to log Redis errors, connection issues, and performance metrics.

Comparing Heroku Redis vs. External Redis Cloud

Feature Heroku Redis Add-on External Redis Service (e.g., Redis Cloud)
Ease of Setup Very easy, single CLI command. Requires separate account setup and manual URL config.
Management Fully managed by Heroku. Managed by the external provider.
Environment Vars REDIS_URL automatically set. Manual heroku config:set REDIS_URL required.
Pricing Integrated with Heroku billing. Separate billing from the external provider.
Advanced Features Good for common use cases, limited advanced config. May offer more advanced features, greater customization.
SLAs/Support Heroku's SLA and support. Provider's specific SLA and support.
Data Residency Tied to Heroku region. Can often choose specific cloud regions/providers.

By following these steps and best practices, you can effectively integrate Redis into your Heroku applications, boosting their performance and functionality.