loading words...

Jan 15, 2019 23:35:03

Rails query performance

by @swizecteller | 207 words | 🐣 | 116💌

Swizec Teller

Current day streak: 0🐣
Total posts: 116💌
Total words: 32303 (129 pages 📄)

Today I spent all day trying to figure out one single function on our backend. The one that hundreds of SQL queries to do one little thing. #200wordsTIL

👉 https://twitter.com/Swizec/status/1083634802194972672

---

Last week I realized that Rails's default query level cache doesn't work so good. You gotta do real caching.

That improved the situation by 50 queries.

But where the hell are the other 200 coming from? How do you find out? Can you enforce some rules? 🤔

---

First: Why care about making many queries? Performance.

The problem isn't database execution, oh no. 

Your database is smart. Your database caches queries with the same result. Reads right from memory. Super fast. 

---

Your database doesn't run on the same machine as your code. Time wasted on internet roundtrips. Hopefully same data center. Maybe same physical machine. 

But you don't know. Could be anywhere. Perhaps half the world apart.

---

Modern architectures: Great for horizontal scale, bad for speedy communication.

---

After much searching I discovered this wonderful gem: rspec-sqlimit

https://github.com/nepalez/rspec-sqlimit

---

With rspec-sqlimit you can write a test that enforces max number of database queries.

And when your code fails, rspec-sqlimit spits out all the queries that ran.

👌

Now I know what to fix, but how!?

Originally published at twitter.com

contact: email - twitter / Terms / Privacy