ileitch/rapns — Issue #29: Major Performance Problem with ready_for_delivery Scope
Author: blakewatters
Created: 2012-01-12 18:51:39+00:00
State: open

We just ran into a nasty issue on production with rapns. The way that the ready_for_delivery scope is written on Rapns::Notification using Arel finders being merged together results in several database queries being issued. Observe:

```
Running console attached to terminal... up, run.1
Loading production environment (Rails 3.1.3)
irb(main):001:0> Rapns::Notification.ready_for_delivery.count
Rapns::Notification Load (22.2ms) SELECT "rapns_notifications".* FROM "rapns_notifications" WHERE (deliver_after IS NULL)
Rapns::Notification Load (1.1ms) SELECT "rapns_notifications".* FROM "rapns_notifications" WHERE (deliver_after < '2012-01-12 18:30:53.706636')
Rapns::Notification Load (0.2ms) SELECT "rapns_notifications".* FROM "rapns_notifications" WHERE "rapns_notifications"."delivered" = 'f' AND "rapns_notifications"."failed" = 'f'
```

The issue is that the first query (deliver_after IS NULL) returns a giant result set. On our production installation, this can retrieve over 100k rows before the secondary notifications cull the result set that is ultimately returned.

Pull request forthcoming.