Question: How to Close Redis Connection?


Closing a Redis connection depends on the programming language and client library you are using. Here, I'll show examples of closing connections in popular languages like Python, Node.js, and Ruby.

Python (Using redis-py)

To close a Redis connection using the redis-py library, you should call the close() method followed by the wait_closed() coroutine function if using an asynchronous connection, or simply the close() method for synchronous connections.

import redis

r = redis.Redis(host='localhost', port=6379)
# perform operations

For async connections:

import aioredis

async def main():
    r = await aioredis.create_redis_pool('redis://localhost')
    # perform operations
    await r.wait_closed()

Node.js (Using ioredis)

To close a Redis connection using the ioredis library, you should call the disconnect() method.

const Redis = require('ioredis');

const redis = new Redis({
  host: 'localhost',
  port: 6379,

// perform operations

Ruby (Using redis-rb)

To close a Redis connection using the redis-rb library, you should call the disconnect! method.

require 'redis'

redis = 'localhost', port: 6379)
# perform operations

Remember to close the connection after you're done with all the required operations to ensure resources are released properly.

Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.