Benchmarking Postgres vs. Redis Reads
I was curious what would be the difference in performance between Postgres and Redis for basic read operations. Redis is highly optimized for writing and reading specific types of data structures, where Postgres, with its ACID guarantees and general-purpose features, can't compete. But for the most basic read operations, where Postgres would keep everything in memory and wouldn't need to lock anything, would the difference in performance be 2x? 10x? 100x? Or not much at all?
So I threw together a simple benchmark. I generated 1000 key/value pairs, and then accessed random values 100,000 times. I also benchmarked a third system: in-memory access to a ruby hash. The results:
- Postgres: 8.9 seconds
- Redis: 5.3 seconds
- Memory: 0.01 seconds
The code is below.
require "pg"
require "redis"
require "faker"
require "benchmark"
redis = Redis.new
redis.flushall
conn = PG.connect( dbname: 'db-benchmark' )
conn.exec <<-SQL
CREATE TABLE IF NOT EXISTS things (
k text,
v text,
PRIMARY KEY (k)
);
TRUNCATE TABLE things;
SQL
memory = {}
(1..1000).each do |k|
v = Faker::Lorem.paragraph(rand 1..10)
conn.exec("insert into things (k, v) values ('#{k}', '#{v}')")
redis.set(k, v)
memory[k]=v
end
n = 100_000
random_keys = []
n.times{random_keys << rand(1..1000)}
Benchmark.bm(10) do |x|
x.report("Postgres") do
n.times do |i|
conn.exec("select v from things where k='#{random_keys[i]}'")
end
end
x.report("Redis") do
n.times do |i|
redis.get(random_keys[i])
end
end
x.report("Memory") do
n.times do |i|
memory[random_keys[i]]
end
end
end