Redis pipelining is a technique that allows you to send multiple commands to Redis in a single batch, significantly reducing network round trip time (RTT) and improving performance. Here’s how to use it in Rails:
# Without pipelining - makes N round trips
redis = Redis.new
100.times do |i|
redis.set("key#{i}", "value#{i}")
end
# With pipelining - makes just 1 round trip
redis = Redis.new
redis.pipelined do
100.times do |i|
redis.set("key#{i}", "value#{i}")
end
end
# You can also get the results of pipelined commands
results = redis.pipelined do
redis.set("foo", "bar")
redis.get("foo")
end
# => ["OK", "bar"]
Be mindful that all commands are stored in memory until executed, so avoid extremely large pipelines.