avoiding n+1 errors in rails apps

13
N+1 Errors

Upload: esther-leytush

Post on 19-Jan-2017

51 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: Avoiding N+1 Errors in Rails Apps

N+1 Errors

Page 2: Avoiding N+1 Errors in Rails Apps

Hi! I’m Esther.I’m a software developer at MarryMapp

and a recent Dev Bootcamp grad(and I <3 Ruby)

estherleytush.com

Page 3: Avoiding N+1 Errors in Rails Apps

This talk was made with newbies in mind.

Page 4: Avoiding N+1 Errors in Rails Apps

What are n+1 errors, in a nutshell?

Page 5: Avoiding N+1 Errors in Rails Apps

Here’s what happens...

Database is queried for

parent record

App needs info about child

records

Database is queried once

per child record

Page 6: Avoiding N+1 Errors in Rails Apps

Products and users:

×An product index page asks for info about some products...

×Then needs to load info about the product creator…

×...querying the database for each creator.

Page 7: Avoiding N+1 Errors in Rails Apps

So, why is this a

problem?

Page 8: Avoiding N+1 Errors in Rails Apps

What if you’re making 100s, 1000s, 10000(...)’s requests? What if your server is far away?

If it takes 1ms to make 1 request, 2ms for 2... Those numbers compound painfully.

Because it slows pages down.

Page 9: Avoiding N+1 Errors in Rails Apps

What would be faster?

Making 1 query with 100 results

instead of 100 queries with 1 result

each.

Page 10: Avoiding N+1 Errors in Rails Apps

Let’s go see it!

Page 11: Avoiding N+1 Errors in Rails Apps

Your Rails tools

:preload:includes:eager_loadPre-make aggregate database queries for the resource you need

Post.preload(:user)

AssociationsPre-make an association for the resource you’ll need in order to preload it

has_one :latest_post, -> { order(created_at: :desc).limit(1) }, class_name: "Post"

Page 12: Avoiding N+1 Errors in Rails Apps

“Try the Bullet gem, too:

It informs you of n+1 errors via excellent logging capability.

Page 13: Avoiding N+1 Errors in Rails Apps

Thanks!

Any questions?estherleytush.comGithub: mindplace