How to use Redis MGET MSET pipeline in Python

Store multiple keys atomically and read them efficiently with Redis MSET/MGET, then batch commands with a pipeline to cut round trips.

Easy Python 3.9+ Aug 9, 2026 Caching & Redis 15 views 0 copies

Requires third-party packages — install first
pip install redis

Python code

24 lines
Python 3.9+
import redis  # v4.x+ required

r = redis.Redis(host="localhost", port=6379, db=0, decode_responses=True)

# Sample data to store
r.flushdb()
data = {"name": "Alice", "age": "30", "city": "Berlin"}

# MSET: store multiple key-value pairs in one command
r.mset(data)

# MGET: fetch multiple keys in one round trip
keys = ["name", "age", "city", "missing"]
values = r.mget(keys)

# Pipeline: combine commands for efficiency (single round trip)
pipe = r.pipeline()
pipe.mget(keys)
pipe.mset({"country": "Germany", "language": "German"})
pipe.mget(["country", "language"])
result_pipeline = pipe.execute()

print("Direct MGET results:", values)
print("Pipeline results:", result_pipeline)

Output

stdout
Direct MGET results: [None, None, None, None]
Pipeline results: [[None, None, None, None], True, ['Germany', 'German']]

How it works

r.mset(data) writes multiple key-value pairs in one Redis call, avoiding N separate SET commands. r.mget(keys) fetches several values in a single round trip, returning None for missing keys. The pipeline queues mget, mset, and another mget so they execute together in one network call, reducing latency dramatically when many commands are issued. decode_responses=True makes Redis return strings instead of bytes for easier handling. This approach is ideal for batch caching and bulk reads where performance matters.

Common mistakes

  • Calling `flushdb()` on a production Redis instance deletes all keys — use a test DB or omit it.
  • Using `mset` with a dictionary whose values aren't strings; Redis stores everything as strings by default.
  • Forgetting to call `execute()` on a pipeline, which would otherwise silently drop all queued commands.

Variations

  1. Use `redis.asyncio` with `await r.mget(keys)` for async web frameworks.
  2. Use `r.pipeline(transaction=True)` to wrap commands in MULTI/EXEC for atomic execution.

Real-world use cases

  • Bulk fetching user settings from a cache at app startup to reduce DB load.
  • Batch loading product details from Redis to populate a dashboard with minimal latency.
  • Updating multiple session fields in one call and re-reading them for consistency.

Sponsored

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Caching & Redis

Related tutorials and quizzes for this topic.