<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by AlekseyL on Medium]]></title>
        <description><![CDATA[Stories by AlekseyL on Medium]]></description>
        <link>https://medium.com/@leshchuk?source=rss-afaaebe85f49------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Aua-QykPuwb2gs-7ogEWFw.png</url>
            <title>Stories by AlekseyL on Medium</title>
            <link>https://medium.com/@leshchuk?source=rss-afaaebe85f49------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 07:14:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@leshchuk/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The battle royal over N+1 in ActiveRecord. Part 2.]]></title>
            <link>https://leshchuk.medium.com/the-battle-royal-over-n-1-in-activerecord-fe1f10b944a7?source=rss-afaaebe85f49------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe1f10b944a7</guid>
            <category><![CDATA[activerecord]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[AlekseyL]]></dc:creator>
            <pubDate>Thu, 03 Jul 2025 11:48:21 GMT</pubDate>
            <atom:updated>2025-07-07T05:14:21.544Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Numbers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IIMN9XVxmmfRMDn9IthvYw.jpeg" /><figcaption>Fool you were, fell you are.</figcaption></figure><p>In <a href="https://leshchuk.medium.com/5ce11870de62">the first part</a> I was digging theeager_load VS preload mechanics, hidden features and corner cases.</p><p>Now lets talk RAM and CPU numbers across multiple rails version.</p><h4>TL;DR*</h4><p>Using findings from the first part, I split the measuring cases into 3 pieces: has_many as usual, has_many through and has_and_belongs_to_many**</p><p><strong>has_many as usual</strong></p><ul><li>preload is <strong>x1.5–2.4 times faster</strong> than eager_load in terms of local CPU** time!</li><li>preload is allways RAM-effective against eager_load. eager_load needs <strong>1.1–1.3 more RAM for retained</strong> and <strong>1.8–2.5 for allocated</strong> objects.</li><li><strong>allocations for rails 8 </strong>spikes on both preload and eager_load — <strong>1.3–1.5</strong> more RAM used, then in earlier rails versions!</li><li><strong>rails_8 </strong><strong>preload</strong> has the <strong>smallest retained memory</strong> size across all rails versions, it needs <strong>0.9 RAM</strong> then earlier version preloads.</li><li><strong>rails_8 </strong><strong>eager_load</strong> has the worst ratio in both<strong> retained x1.08</strong> and <strong>allocated x1.5-1.65</strong> memory among all later rails versions.</li></ul><p><strong>has_and_belongs_to_many</strong></p><ul><li>preload uses slightly <strong>more RAM</strong> thaneager_laod , but they are close: <strong>1.02–1.08</strong>.</li><li><strong>eager_load</strong> <strong>is</strong> <strong>x1.3 faster</strong> then preload in terms of local CPU***.</li><li><strong>rails 7.0</strong> is the fastest for both preload and eager_loadacross all measured rails versions, it’s <strong>x1.15 faster than 6 and 8</strong></li><li>preload is ~ <strong>x1.1 faster in DB </strong>requests!</li></ul><p><strong>has_many through</strong></p><p>Exact numbers and ratios are irrelevant here since, when you avoid through relations from being loaded, eager_loadwill be much more effective in both CPU and RAM. I’ve got <strong>x3–4 less RAM</strong>, and <strong>x2.5 faster</strong> local CPU** when eager_load keeps <strong>two out of four</strong> relations.</p><p><strong>DB</strong></p><p>Despite the fact thateager_load <em>sometimes</em> run less queries, overhead for the JOIN and bigger raw dataset is noticeble enough on DB level so eager_load is faster only on a small dataset with nesting around 2 relations deep. For big enough dataset, in my case starting somewhere around 15 root elements, it’s faster for preload to go to DB couple times more, than have enormous JOIN and return everything in one piece.</p><blockquote>*Comparisons were maid for collections with LIMIT clause applied! In case of limitless connection eager_loading will have an advantage of a single query.</blockquote><blockquote>** Even though has_and_belongs_to_many could be considered a special case for has_many through I’ve extracted it to a standalone case.</blockquote><blockquote>*** That’s excluding DB numbers, even though they are usually less for preload, I decided to exclude them from measuring.</blockquote><h4>Tools</h4><p>I’m gonna run code under ruby 3.4.1, use bmbm* with rehersal, rawmemory_profiler , rails 6.1/7.x/8.0 and terminal-table to format the output.</p><pre>gem &quot;memory_profiler&quot;<br>gem &quot;terminal-table&quot;</pre><blockquote>*I not using ips cause it’s less informative here and because I can’t run ips benchmark across multiple rails versions.</blockquote><h4>Relations</h4><p>Here are the relations definitions with some additional info around them:</p><pre># I think following naming is selfexplanatory so no additional comments needed<br>class Course<br>  # simple structure, 147 bytes avg record size, <br>  # average amount of topics ~ 4 per course <br>  has_many :topics<br>  # medium complexity structure, 383 bytes avg size, up to 38kb<br>  # average amount of lessons ~ 6 per topic<br>  has_many :lessons, through: :topics<br>  # average amount of homeworks per lesson ~ 1<br>  has_many :homeworks, through: :lessons<br>  # complex content data, 1.4Kb average size of a record, up to 0.7Mb<br>  # average amount of task_cards per homework ~ 5<br>  has_many :homework_task_cards, through: :homeworks, class_name: :TaskCard<br>end<br><br>class CourseSession<br>  has_and_belongs_to_many :teachers, join_table: :teachers_course_sessions<br>end<br><br># complex content data, 6.8Kb average size of a record, up to 35Kb<br>class PublicMaterial<br>  # simple structure, average size 0.4kb<br>  has_and_belongs_to_many :categories, join_table: :categories_public_materials<br>end</pre><h4>Vanilla numbers RAM</h4><p>To be honest I wasn’t expected much from rails version to version comparision, but the findings were interesting and I’ve end up running all tests across three rails versions.</p><h4>has_many as usual</h4><p>For a code sample look at a <strong>Gists</strong> section at the bottom. Here is the numbers:</p><pre># 100 random courses with topics, <br># Course.preload(:topics) VS Course.eager_load(:topics)<br><br># Rails 6.1<br>+------------+-----------------------------+------------------------------+<br>| Methods    | Retained                    | Allocated                    |<br>+------------+-----------------------------+------------------------------+<br>| preload    | 1.07 MB(obj: 7746) x 1.0    | 1.4 MB(obj: 12068) x 1.0     |<br>| eager_load | 1.17 MB(obj: 8155) x 1.09   | 2.64 MB(obj: 15784) x 1.88   |<br>+------------+-----------------------------+------------------------------+<br><br># Rails 7.0<br>+------------+----------------------------+------------------------------+<br>| Methods    | Retained                   | Allocated                    |<br>+------------+----------------------------+------------------------------+<br>| preload    | 1.1 MB(obj: 7830) x 1.0    | 1.44 MB(obj: 12245) x 1.0    |<br>| eager_load | 1.2 MB(obj: 8245) x 1.09   | 2.71 MB(obj: 16290) x 1.87   |<br>+------------+----------------------------+------------------------------+<br><br># Rails 8.0 (!!!)<br>+------------+-----------------------------+------------------------------+<br>| Methods    | Retained                    | Allocated                    |<br>+------------+-----------------------------+------------------------------+<br>| preload    | 1.0  MB(obj: 7921) x 1.0    | 1.79 MB(obj: 15479) x 1.0    |<br>| eager_load | 1.29 MB(obj: 7743) x 1.32   | 4.09 MB(obj: 23689) x 2.28   |<br>+------------+-----------------------------+------------------------------+<br><br><br># Rails version to versions comparisons ( fixed set of objects )<br>+------------+-----------------------------+------------------------------+<br>| Methods    | Retained                    | Allocated                    |<br>+------------+-----------------------------+------------------------------+<br>| Preload                                                                 |<br>+------------+-----------------------------+------------------------------+<br>| rails 6.1  | 1.19 MB(obj: 8427) x 1.1    | 1.54 MB(obj: 13060)          |<br>| rails 7.0  | 1.2 MB(obj: 8426)  x 1.11   | 1.56 MB(obj: 13104) x 1.01   |<br>| rails 8.0  | 1.08 MB(obj: 8571)          | 1.96 MB(obj: 16625) x 1.27   |<br>+------------+-----------------------------+------------------------------+<br>| Eager_load                                                              |<br>+------------+-----------------------------+------------------------------+<br>| rails 6.1  | 1.31 MB(obj: 8894)          | 3.02 MB(obj: 18070)          |<br>| rails 7.0  | 1.32 MB(obj: 8894) x 1.00   | 3.05 MB(obj: 18379) x 1.01   |<br>| rails 8.0  | 1.42 MB(obj: 8394) x 1.08   | 4.63 MB(obj: 26967) x 1.53   |<br>+------------+-----------------------------+------------------------------+</pre><p>Lets look at numbers from two levels nesting:</p><pre># 100 random courses with topics and lessons,<br>## Course.preload(topics: :lessons) VS Course.eager_load(topics: :lessons)<br><br># rails 6.1<br>+------------+------------------------------+-------------------------------+<br>| Methods    | Retained                     | Allocated                     |<br>+------------+------------------------------+-------------------------------+<br>| preload    | 8.87 MB(obj: 44052) x 1.0    | 10.7 MB(obj: 66918) x 1.0     |<br>| eager_load | 9.52 MB(obj: 46928) x 1.07   | 22.8 MB(obj: 100218) x 2.12   |<br>+------------+------------------------------+-------------------------------+<br><br># rails 7.0<br>+------------+-----------------------------+-----------------------------+<br>| Methods    | Retained                    | Allocated                   |<br>+------------+-----------------------------+-----------------------------+<br>| preload    | 8.21 MB(obj: 41109) x 1.0   | 9.99 MB(obj: 62406) x 1.0   |<br>| eager_load | 8.8 MB(obj: 43755) x 1.07   | 21 MB(obj: 93657) x 2.1     |<br>+------------+-----------------------------+-----------------------------+<br><br># rails 8.0<br>+------------+------------------------------+-------------------------------+<br>| Methods    | Retained                     | Allocated                     |<br>+------------+------------------------------+-------------------------------+<br>| preload    | 9.84 MB(obj: 51355) x 1.0    | 18.8 MB(obj: 98831) x 1.0     |<br>| eager_load | 12.4 MB(obj: 51150) x 1.26   | 45.8 MB(obj: 192930) x 2.43   |<br>+------------+------------------------------+-------------------------------+<br><br># Rails version to versions comparisons ( fixed set of objects )<br>+------------+-----------------------------+------------------------------+<br>| Methods    | Retained                    | Allocated                    |<br>+------------+-----------------------------+------------------------------+<br>| Preload                                                                 |<br>+------------+-----------------------------+------------------------------+<br>| rails 6.1  | 8.69 MB(obj: 56838) x 1.16  | 11.1 MB(obj: 86194)          |<br>| rails 7.0  | 8.75 MB(obj: 56837) x 1.17  | 11.2 MB(obj: 85891)  x 1.01  |<br>| rails 8.0  | 7.46 MB(obj: 57076)         | 13.9 MB(obj: 109588) x 1.25  |<br>+------------+-----------------------------+------------------------------+<br>| Eager_load                                                              |<br>+------------+-----------------------------+------------------------------+<br>| rails 6.1  | 9.55 MB(obj: 60640)         | 27.2 MB(obj: 128157)         |<br>| rails 7.0  | 9.6  MB(obj: 60640) x 1.00  | 27.4 MB(obj: 131777)         |<br>| rails 8.0  | 10.3 MB(obj: 56796) x 1.08  | 45.1 MB(obj: 214746) x 1.65  |<br>+------------+-----------------------------+------------------------------+</pre><p>Going 3-4 levels nesting brings same ratio numbers so I’ll just put them at the Appendix part. Same for smaller collection size, ratio between retained objects stands. Ratio between allocations sometimes drastically spikes, but could be lesser also.</p><h4>HABTM and preload</h4><p>As we uncovered in the first part preload overhas_and_belongs_to_many instatiates +1 hidden relation for a join table, even though intermediate relation as tiny as possible, there will be some overhead, here is the numbers:</p><pre># HABTM public_materials &lt;-&gt; caterogies 100 same set for each rails version<br><br># rails 6.1<br>+------------+-----------------------------+-----------------------------+<br>| Methods    | Retained                    | Allocated                   |<br>+------------+-----------------------------+-----------------------------+<br>| eager_load | 3.22 MB(obj: 2214) x 1.0    | 3.68 MB(obj: 5639) x 1.0 )  |<br>| preload    | 3.35 MB(obj: 3478) x 1.03   | 3.62 MB(obj: 7837) x 0.98 ) |<br>+------------+-----------------------------+-----------------------------+<br><br># rails 7.0<br><br>+------------+----------------------------+----------------------------+<br>| Methods    | Retained                   | Allocated                  |<br>+------------+----------------------------+----------------------------+<br>| eager_load | 3,2 МБ(obj: 2214) x 1.0    | 3,7 МБ(obj: 5473) x 1.0    |<br>| preload    | 3,4 МБ(obj: 3478) x 1.04   | 3,7 МБ(obj: 8051) x 0.99   |<br>+------------+----------------------------+----------------------------+<br><br># rails 8<br>+------------+-----------------------------+-----------------------------+<br>| Methods    | Retained                    | Allocated                   |<br>+------------+-----------------------------+-----------------------------+<br>| eager_load | 3.24 MB(obj: 2209) x 1.0    | 6.87 MB(obj: 6197) x 1.0    |<br>| preload    | 3.34 MB(obj: 3623) x 1.02   | 6.62 MB(obj: 8152) x 0.96   |<br>+------------+-----------------------------+-----------------------------+<br><br><br># HABTM course_sessions &lt;-&gt; teachers 100 same set for each rails version <br><br># rails 6.1<br>+------------+----------------------------+------------------------------+<br>| Methods    | Retained                   | Allocated                    |<br>+------------+----------------------------+------------------------------+<br>| eager_load | 515 KB(obj: 3509) x 1.0    | 1.59 MB(obj: 9992) x 1.0     |<br>| preload    | 549 KB(obj: 3933) x 1.06   | 1.63 MB(obj: 14993) x 1.02   |<br>+------------+----------------------------+------------------------------+<br><br># rails 7.0<br>+------------+------------------------------+-----------------------------+<br>| Methods    | Retained                     | Allocated                   |<br>+------------+------------------------------+-----------------------------+<br>| eager_load | 524.7 KB(obj: 3509) x 1.0    | 1.6 MB(obj: 9344) x 1.0     |<br>| preload    | 568.5 KB(obj: 3933) x 1.08   | 1.6 MB(obj: 13974) x 1.02   |<br>+------------+------------------------------+-----------------------------+<br><br>#rails 8<br>+------------+------------------------------+-----------------------------+<br>| Methods    | Retained                     | Allocated                   |<br>+------------+------------------------------+-----------------------------+<br>| eager_load | 549.7 KB(obj: 3504) x 1.0    | 2.5 MB(obj: 13419) x 1.13   |<br>| preload    | 567.6 KB(obj: 4039) x 1.03   | 2.2 MB(obj: 17669) x 1.0    |<br>+------------+------------------------------+-----------------------------+</pre><p>eager_load retain objects memory is slightly less then preload retentions, with parity on allocations for rails 6.1/7.0.</p><p><strong>Rails 8</strong> memory usage grows same as has_many did ~7%, and still <strong>sucks on allocatio</strong>n, it will use <strong>1.5–1.8 times more memory</strong> than 6.1 or 7.0 during that phase.</p><p>This ratios are stable and do not change with the size growth of a basic collection.</p><h4>Skipping through models by eager_load</h4><p>As we saw in <a href="https://leshchuk.medium.com/5ce11870de62">the first part</a>, railspreload for through association loads all related objects alongside the path to preloaded relation, and the eager_load uses exact JOIN and skips intermediate relations.</p><p>That’s why the following case should be considered as a random example verifying expectations with some exact numbers.</p><p>In a given example eager_load loads two models and skip the other two, preload — loads all four, so the RAM numbers differs <strong>3–4 times</strong>.</p><pre># Course.preload(:homeworks) VS Course.eager_load(:homeworks) <br># course -&gt; ( topics -&gt; lessons ) -&gt; homeworks<br># 100 randomly selected courses, same collection for each rails version<br><br># rails 6.1<br>+------------+------------------------------+------------------------------+<br>| Methods    | Retained                     | Allocated                    |<br>+------------+------------------------------+------------------------------+<br>| eager_load | 4.87 MB(obj: 28944) x 1.0    | 14.6 MB(obj: 70443) x 1.0    |<br>| preload    | 19.8 MB(obj: 98933) x 4.06   | 24.9 MB(obj: 168295) x 1.7   |<br>+------------+------------------------------+------------------------------+<br><br># rails 7.0<br>+------------+------------------------------+-------------------------------+<br>| Methods    | Retained                     | Allocated                     |<br>+------------+------------------------------+-------------------------------+<br>| eager_load | 4,9 МБ(obj: 28944) x 1.0     | 14,6 МБ(obj: 70265) x 1.0     |<br>| preload    | 20,2 МБ(obj: 98933) x 4.13   | 25,5 МБ(obj: 171946) x 1.74   |<br>+------------+------------------------------+-------------------------------+<br><br># rails 8<br>+------------+-------------------------------+------------------------------+<br>| Methods    | Retained                      | Allocated                    |<br>+------------+-------------------------------+------------------------------+<br>| eager_load | 5,3 МБ(obj: 28976) x 1.0      | 23,3 МБ(obj: 120507) x 1.0   |<br>| preload    | 19,1 МБ(obj: 102419) x 3.56   | 37,5 МБ(obj: 225892) x 1.6   |<br>+------------+-------------------------------+------------------------------+ </pre><h4>Vanilla numbers CPU</h4><p>As I’ve already mentioned CPU measured with a rehearsal, and from my observations, numbers are stable, and valid for the comparison.</p><pre># Course.preload(:topics) VS Course.eager_load(:topics), <br># colection size 100, iterations amount -- 50, <br><br># rails 6.1<br>Rehearsal ----------------------------------------------<br>                  user     system      total        real       DB<br>preload      0.989608   0.050481   1.040089 (  1.524629)  0.484539<br>eager_load   1.229615   0.076655   1.306270 (  1.879801)  0.573531<br>------------------------------------- total: 2.346359sec<br><br>                 user     system      total        real        DB<br>preload      0.777332   0.039486   0.816818 (  1.294002)  0.47718<br>eager_load   1.184600   0.056368   1.240968 (  1.838377)  0.59741<br><br># rails 7.0<br>Rehearsal ----------------------------------------------<br>                  user     system      total        real       DB<br>preload      1.053129   0.044235   1.097364 (  1.600092)  0.47205<br>eager_load   1.290743   0.073286   1.364029 (  1.943127)  0.57910<br>------------------------------------- total: 2.461393sec<br><br>                 user     system      total        real        DB<br>preload      0.807896   0.026954   0.834850 (  1.306899)  0.47205<br>eager_load   1.288338   0.035741   1.324079 (  1.894925)  0.57085<br><br><br># rails 8.0<br>Rehearsal ----------------------------------------------<br>                 user     system      total        real       DB<br>preload      0.904890   0.037519   0.942409 (  1.424775)  0.48237<br>eager_load   1.575442   0.055172   1.630614 (  2.218060)  0.58745<br>------------------------------------- total: 2.573023sec<br><br>                 user     system      total        real       DB<br>preload      0.891283   0.043763   0.935046 (  1.405053)  0.47001<br>eager_load   1.564264   0.072769   1.637033 (  2.212200)  0.57517<br><br><br># By versions: <br># Rails version to versions comparisons <br>+------------+----------+----------+-----------------+----------+---------+<br>| Methods    |   user   |  system  |   total         |   real   |  DB     |<br>+------------+--------------------------------------------------+---------+<br>| Preload                                                                 |  <br>+------------+--------------------------------------------------+---------+<br>| rails 6.1  | 0.777332 | 0.039486 | 0.816818        | 1.294002 | 0.47718 |<br>| rails 7.0  | 0.807896 | 0.026954 | 0.834850 x 1.02 | 1.306899 | 0.47205 |<br>| rails 8.0  | 0.891283 | 0.043763 | 0.935046 x 1.14 | 1.405053 | 0.47001 |<br>+------------+------------------------------------------------------------+<br>| Eager_load                                                              |<br>+------------+------------------------------------------------------------+<br>| rails 6.1  | 1.184600 | 0.056368 | 1.240968        | 1.838377 | 0.59741 |<br>| rails 7.0  | 1.288338 | 0.035741 | 1.324079 x 1.07 | 1.894925 | 0.57085 |<br>| rails 8.0  | 1.564264 | 0.072769 | 1.637033 x 1.32 | 2.212200 | 0.57517 |<br>+------------+----------+----------+-----------------+--------------------+</pre><blockquote>What’s interesting from bm measuring (instead of ips): you can easily measure DB + roundtrips overhead here, just substract real — total columns, and you will see that this difference nearly is the same across different rails versions, cause the amount and structure of queries match!</blockquote><p>At first I wasn’t planning on explicitly measuring DB additions, but then I’ve got curious, and got some very interesting numbers and conclusions from that.</p><p>Two levels nesting:</p><pre># Course.preload(topics: :lessons) VS Course.eager_load(topics: :lessons), <br># colection size 100, iterations amount -- 50, <br><br># rails 6.1<br>Rehearsal ----------------------------------------------<br>                 user     system      total        real       DB<br>preload      5.163399   0.361778   5.525177 (  7.155274)  1.6301<br>eager_load   8.510954   0.538402   9.049356 ( 11.059861)  2.0105<br>------------------------------------ total: 14.574533sec<br><br>                 user     system      total        real       DB<br>preload      5.036750   0.319098   5.355848 (  6.902156)  1.5463<br>eager_load   8.682310   0.472692   9.155002 ( 10.787932)  1.6329<br><br><br># rails 7.0<br>Rehearsal ----------------------------------------------<br>                 user     system      total        real       DB<br>preload      6.453466   0.400456   6.853922 (  8.449075)  1.5952<br>eager_load   8.601520   0.563142   9.164662 ( 11.023966)  1.8593  <br>------------------------------------ total: 16.018584sec<br><br>                 user     system      total        real       DB<br>preload      4.988292   0.363969   5.352261 (  7.013981)  1.6617<br>eager_load   8.586447   0.509541   9.095988 ( 10.856262)  1.7603<br><br><br>#rails 8.0<br>Rehearsal ----------------------------------------------<br>                 user     system      total        real       DB<br>preload      5.883184   0.326428   6.209612 (  7.801933)  1.5923<br>eager_load  11.673592   0.539979  12.213571 ( 13.922825)  1.7092<br>------------------------------------ total: 18.423183sec<br><br>                 user     system      total        real       DB<br>preload      5.746900   0.347506   6.094406 (  7.699330)  1.6049<br>eager_load  11.294527   0.540016  11.834543 ( 13.614513)  1.7799<br><br><br># Rails version to versions comparisons<br>+------------+----------+----------+-----------------+----------+---------+<br>| Methods    |   user   |  system  |   total         |   real   |   DB    |<br>+------------+--------------------------------------------------+---------+<br>| Preload                                                                 |<br>+------------+--------------------------------------------------+---------+<br>| rails 6.1  | 5.036750 | 0.319098 | 5.355848 x 1.00 | 6.902156 | 1.54631 |<br>| rails 7.0  | 4.988292 | 0.363969 | 5.352261        | 7.013981 | 1.66172 |<br>| rails 8.0  | 5.746900 | 0.347506 | 6.094406 x 1.13 | 7.699330 | 1.60492 |<br>+------------+------------------------------------------------------------+<br>| Eager_load                                                              |<br>+------------+------------------------------------------------------------+<br>| rails 6.1  | 8.682310 | 0.472692 | 9.155002 x 1.00 | 10.78793 | 1.63293 |<br>| rails 7.0  | 8.586447 | 0.509541 | 9.095988        | 10.85626 | 1.76027 |<br>| rails 8.0  | 11.29453 | 0.540016 | 11.83454 x 1.30 | 13.61451 | 1.77996 |<br>+------------+----------+----------+-----------------+--------------------+</pre><p>Going 4 levels of nesting gives the same ratios, see appendix section.</p><p>So <strong>eager_load looses every contest here</strong>, skipinng couple roundtrips to DB only slightly affect the ratio, but the complexity of the multiple JOIN&#39;s and result parsing and assignment from DB raw data to ORM is so huge, so couple ms for the roundtrip comes unnoticable!</p><p>In numbers full ratio including DB: starts from x1.15, for the 10 elements 2-level deep collections, which is optimal for eager_load, ends up 2 times slower for bigger collection and deeper nesting.</p><p>And comparing times spent processing collection inside local machine: preload is <strong>x1.5–2.4 times faster</strong> than eager_load !</p><p><strong>HABTM on CPU</strong></p><p>I’ve expected some overhead for the preload and numbers vary depending on the models involved. In my case for combination public_materials &lt;-&gt; categories 1.0–1.1 in favor of eager_load for rails 6/7, and upto x1.15 for rails 8, as for cobmination course_sessions &lt;-&gt; teachers ~ 1.3 in favor of eager_load across all versions of rails. But DB part is ~1.1 faster in favour of preload! This came unexpected.</p><pre># CourseSession.preload(:teachers) VS CourseSession.eager_load(:teachers),<br># colection size 100, iterations amount -- 50, <br><br># rails 6.1<br>Rehearsal ----------------------------------------------<br>                 user     system      total        real         DB<br>preload      1.108736   0.035008   1.143744 (  1.716962)  0.573218<br>eager_load   0.889584   0.038247   0.927831 (  1.522479)  0.594648<br>------------------------------------- total: 2.071575sec<br><br>                 user     system      total        real        DB<br>preload      1.073060   0.035690   1.108750 (  1.686948)  0.57820<br>eager_load   0.793296   0.051055   0.844351 (  1.457465)  0.61311<br><br># rails 7.0<br>Rehearsal ----------------------------------------------<br>                 user     system      total        real        DB<br>preload      1.017093   0.027162   1.044255 (  1.610298)  0.56604<br>eager_load   0.745156   0.024761   0.769917 (  1.374575)  0.60466<br>------------------------------------- total: 1.814172sec<br><br>                 user     system      total        real        DB<br>preload      0.929101   0.050232   0.979333 (  1.535041)  0.55571<br>eager_load   0.723043   0.027391   0.750434 (  1.390913)  0.64048<br><br><br>#rails 8.0<br>Rehearsal ---------------------------------------------- <br>                 user     system      total        real        DB<br>preload      1.118909   0.009697   1.128606 (  1.711502)  0.58290<br>eager_load   0.856780   0.030068   0.886848 (  1.541684)  0.65483<br>------------------------------------- total: 2.015454sec<br><br>                 user     system      total        real        DB<br>preload      1.106693   0.053913   1.160606 (  1.770954)  0.61035<br>eager_load   0.823645   0.035660   0.859305 (  1.509399)  0.65009<br><br><br># By versions: <br># Rails version to versions comparisons<br>+------------+----------+----------+-----------------+----------+--------+<br>| Methods    |   user   |  system  |   total         |   real   |   DB   |<br>+------------+--------------------------------------------------+--------+<br>| Preload                                                                |<br>+------------+--------------------------------------------------+--------+<br>| rails 6.1  | 1.073060 | 0.035690 | 1.108750 x 1.13 | 1.686948 | 0.5782 |<br>| rails 7.0  | 0.929101 | 0.050232 | 0.979333        | 1.535041 | 0.5557 |<br>| rails 8.0  | 1.106693 | 0.053913 | 1.160606 x 1.18 | 1.770954 | 0.6104 |<br>+------------+-----------------------------------------------------------+<br>| Eager_load                                                             |<br>+------------+-----------------------------------------------------------+<br>| rails 6.1  | 0.793296 | 0.051055 | 0.844351 x 1.13 | 1.457465 | 0.6131 |<br>| rails 7.0  | 0.723043 | 0.027391 | 0.750434        | 1.390913 | 0.6405 |<br>| rails 8.0  | 0.823645 | 0.035660 | 0.859305 x 1.15 | 1.509399 | 0.6501 |<br>+------------+----------+----------+-----------------+-------------------+</pre><p>While the numbers for preload VS eager_load is something I’ve expected, yet rails to rails comparisons comes with a surprize: rails 7 is around x1.15 faster then rails 6 and 8 for HABTM relations!</p><h4>Skipping through models by eager_load</h4><p>This measuring is just an example, of how nubmers may differ when intermediate collections skipped.</p><pre># CourseSession.preload(:homeworks) VS CourseSession.eager_load(:homeworks),<br># colection size 100, iterations amount -- 50, <br><br># rails 6.1<br>Rehearsal ----------------------------------------------<br>preload     10.061732   0.445985  10.507717 ( 13.375036)<br>eager_load   4.496814   0.266833   4.763647 (  6.402852)<br>------------------------------------ total: 15.271364sec<br><br>                 user     system      total        real<br>preload     10.310909   0.498494  10.809403 ( 13.569513)<br>eager_load   4.488124   0.281416   4.769540 (  6.329011)<br><br><br># rails 7.0<br>Rehearsal ----------------------------------------------<br><br>preload     10.010192   0.374849  10.385041 ( 13.082086)<br>eager_load   4.254862   0.174703   4.429565 (  5.998558)<br>------------------------------------ total: 14.814606sec<br><br>                 user     system      total        real<br>preload     10.200735   0.411603  10.612338 ( 13.636702)<br>eager_load   4.104362   0.235949   4.340311 (  6.009613)<br><br>#rails 8.0<br>Rehearsal ----------------------------------------------<br><br>preload     11.312790   0.386001  11.698791 ( 14.518222)<br>eager_load   5.879453   0.227304   6.106757 (  7.684735)<br>------------------------------------ total: 17.805548sec<br><br>                 user     system      total        real<br>preload     10.772261   0.370846  11.143107 ( 13.839800)<br>eager_load   5.609008   0.220383   5.829391 (  7.401301)<br><br><br># By versions: <br># Rails version to versions comparisons<br>+------------+----------+----------+-----------------+----------+--------+<br>| Methods    |   user   |  system  |   total         |   real   |   DB   |<br>+------------+--------------------------------------------------+--------+<br>| Preload                                                                |<br>+------------+--------------------------------------------------+--------+<br>| rails 6.1  | 10.31091 | 0.498494 | 10.80940 x 1.02 | 13.56951 | 2.7601 |<br>| rails 7.0  | 10.20073 | 0.411603 | 10.61234        | 13.63670 | 3.0244 |<br>| rails 8.0  | 10.77226 | 0.370846 | 11.14311 x 1.05 | 13.83980 | 2.6967 |<br>+------------+-----------------------------------------------------------+<br>| Eager_load                                                             |<br>+------------+-----------------------------------------------------------+<br>| rails 6.1  | 4.488124 | 0.281416 | 4.769540 x 1.1  | 6.329011 | 0.6131 |<br>| rails 7.0  | 4.104362 | 0.235949 | 4.340311        | 6.009613 | 0.6405 |<br>| rails 8.0  | 5.609008 | 0.220383 | 5.829391 x 1.34 | 7.401301 | 0.6501 |<br>+------------+----------+----------+-----------------+-------------------+</pre><h4>Conclusion</h4><p>preload is a chosen one by the @dhh and rails themselves, and now you can see why. Unless you are cheeting with through relations, it’s winning everything and everywhere*. Also it got noticeably better in the current latest version of the rails (8.0), and the eager_load on the opposite got slower and RAM-suffocating. Even on DB-level eager_load sucks. If you want real numbers on how badly eager_load sucks re-read the TL;DR section.</p><blockquote>*it’s not completely winning habtm, I would say it’s a draw by split decision.</blockquote><h4>Appendix</h4><p>Additional relation comparisons</p><pre><br># 100 random courses with topics, lessons, homeworks and task_cards<br><br># rails 6.1<br>+------------+-------------------------------+------------------------------+<br>| Methods    | Retained                      | Allocated                    |<br>+------------+-------------------------------+------------------------------+<br>| preload    | 42.8 MB(obj: 224335) x 1.0    | 53.8 MB(obj: 370196) x 1.0 ) |<br>| eager_load | 45.6 MB(obj: 236674) x 1.06   | 115 MB(obj: 490304) x 2.13 ) |<br>+------------+-------------------------------+------------------------------+<br><br># rails 7.0<br>+------------+-------------------------------+------------------------------+<br>| Methods    | Retained                      | Allocated                    |<br>+------------+-------------------------------+------------------------------+<br>| preload    | 39.7 MB(obj: 184942) x 1.0    | 49.5 MB(obj: 316929) x 1.0 ) |<br>| eager_load | 41.9 MB(obj: 195283) x 1.05   | 107 MB(obj: 407025) x 2.15 ) |<br>+------------+-------------------------------+------------------------------+<br><br># rails 8.0<br>+------------+-------------------------------+------------------------------+<br>| Methods    | Retained                      | Allocated                    |<br>+------------+-------------------------------+------------------------------+<br>| preload    | 35.2 MB(obj: 217146) x 1.0    | 68.3 MB(obj: 456325) x 1.0   |<br>| eager_load | 43.6 MB(obj: 216816) x 1.24   | 176 MB(obj: 792181) x 2.57   |<br>+------------+-------------------------------+------------------------------+<br><br><br><br># 100 fixed set of courses with topics, lessons, homeworks and task_cards<br># rails 6.1<br>+------------+-------------------------------+------------------------------+<br>| Methods    | Retained                      | Allocated                    |<br>+------------+-------------------------------+------------------------------+<br>| preload    | 57.9 MB(obj: 306176) x 1.0    | 73.1 MB(obj: 506132) x 1.0   |<br>| eager_load | 61.6 MB(obj: 322476) x 1.06   | 136 MB(obj: 672145) x 1.86   |<br>+------------+-------------------------------+------------------------------+<br><br># rails 7.0<br>+------------+-------------------------------+------------------------------+<br>| Methods    | Retained                      | Allocated                    |<br>+------------+-------------------------------+------------------------------+<br>| preload    | 58.5 MB(obj: 305396) x 1.0    | 73.7 MB(obj: 507950) x 1.0   |<br>| eager_load | 62.2 MB(obj: 322464) x 1.06   | 138 MB(obj: 698908) x 1.87   |<br>+------------+-------------------------------+------------------------------+<br><br># rails 8.0 <br>+------------+-------------------------------+-------------------------------+<br>| Methods    | Retained                      | Allocated                     |<br>+------------+-------------------------------+-------------------------------+<br>| preload    | 53.5 MB(obj: 306788) x 1.0    | 105 MB(obj: 642979) x 1.0     |<br>| eager_load | 65.5 MB(obj: 305343) x 1.22   | 229 MB(obj: 1156938) x 2.19   |<br>+------------+-------------------------------+-------------------------------+ </pre><p>HABTM RAM additionals.</p><pre># course_sessions &lt;-&gt; teachers 1K randomly selected and then fixed set<br><br># rails 6.1<br>+------------+-----------------------------+------------------------------+<br>| Methods    | Retained                    | Allocated                    |<br>+------------+-----------------------------+------------------------------+<br>| eager_load | 2.87 MB(obj: 20135) x 1.0   | 13.7 MB(obj: 82186) x 1.0    |<br>| preload    | 3.18 MB(obj: 24159) x 1.1   | 13.7 MB(obj: 129093) x 1.0   |<br>+------------+-----------------------------+------------------------------+<br><br># rails 7.0<br>+------------+-----------------------------+-------------------------------+<br>| Methods    | Retained                    | Allocated                     |<br>+------------+-----------------------------+-------------------------------+<br>| eager_load | 3.0 MB(obj: 20135) x 1.0    | 13.6 MB(obj: 77775) x 1.0     |<br>| preload    | 3.4 MB(obj: 24159) x 1.13   | 13.5 MB(obj: 117203) x 0.98   |<br>+------------+-----------------------------+-------------------------------+<br><br># rails 8.0<br>+------------+-----------------------------+-------------------------------+<br>| Methods    | Retained                    | Allocated                     |<br>+------------+-----------------------------+-------------------------------+<br>| eager_load | 3.1 MB(obj: 20130) x 1.0    | 22.6 MB(obj: 117906) x 1.0    |<br>| preload    | 3.3 MB(obj: 25165) x 1.04   | 19.0 MB(obj: 153256) x 0.84   |<br>+------------+-----------------------------+-------------------------------+</pre><p>100 elems collection, 4 levels nesting numbers, CPU measuring:</p><pre># Course.preload(topics: {lessons: {homeworks: :task_cards} }) <br>#                          VS <br># Course.eager_load(topics: {lessons: {homeworks: :task_cards} }), <br># colection size 100, iterations amount -- 50, <br><br># rails 6.1<br>Rehearsal ----------------------------------------------<br>                 user     system      total        real        DB<br>preload     27.495163   1.743459  29.238622 ( 38.748156)   9.5095<br>eager_load  45.123995   3.280908  48.404903 ( 60.114884)  11.7099<br>------------------------------------ total: 77.643525sec<br><br>                 user     system      total        real        DB<br>preload     26.462787   1.481489  27.944276 ( 37.012916)   9.0686<br>eager_load  47.468294   3.055346  50.523640 ( 61.518940)  10.9953<br><br><br># rails 7.0<br>Rehearsal ----------------------------------------------<br>                 user     system      total        real        DB<br>preload     26.340307   1.691753  28.032060 ( 37.246539)   9.2144<br>eager_load  47.433690   2.970624  50.404314 ( 61.296225)  10.8919 <br>------------------------------------ total: 78.436374sec<br><br>                 user     system      total        real       DB<br>preload     25.895083   1.419553  27.314636 ( 36.837528)  9.5229<br>eager_load  43.167376   2.984398  46.151774 ( 57.034994) 10.8832<br> <br><br>#rails 8.0<br>Rehearsal ----------------------------------------------<br>                 user     system      total        real       DB<br>preload     30.369594   1.602551  31.972145 ( 40.656333)  8.6841<br>eager_load  66.475606   3.427888  69.903494 ( 80.681942) 10.7784<br>----------------------------------- total: 101.875639sec<br><br>                 user     system      total        real       DB<br>preload     29.280195   1.811869  31.092064 ( 39.871801)  8.7797<br>eager_load  61.446797   3.370226  64.817023 ( 75.105993) 10.2890</pre><p>10 elems collection, 4 levels nesting numbers, CPU measuring:</p><pre># Course.preload(topics: {lessons: {homeworks: :task_cards} }) <br>#                          VS <br># Course.eager_load(topics: {lessons: {homeworks: :task_cards} }), <br># colection size 10, iterations amount -- 50, <br><br># rails 6.1<br><br>Rehearsal ----------------------------------------------<br>                 user     system      total        real        DB<br>preload      3.481905   0.266796   3.748701 (  5.618799)   1.8701<br>eager_load   4.946779   0.394603   5.341382 (  7.015843)   1.6745 <br>------------------------------------- total: 9.090083sec<br><br>                 user     system      total        real       DB<br>preload      2.920290   0.175446   3.095736 (  4.898855)   1.8031<br>eager_load   4.662621   0.463635   5.126256 (  6.923566)   1.7973<br><br><br># rails 7.0<br>Rehearsal ----------------------------------------------<br>                 user     system      total        real       DB<br>preload      3.277319   0.239584   3.516903 (  5.426403)   1.9095<br>eager_load   4.482845   0.428514   4.911359 (  6.569686)   1.6583<br>------------------------------------- total: 8.428262sec<br><br>                 user     system      total        real       DB<br>preload      2.773710   0.191719   2.965429 (  4.791486)   1.8261<br>eager_load   4.928123   0.344201   5.272324 (  6.897298)   1.6250<br><br>#rails 8.0<br>Rehearsal ----------------------------------------------<br>                 user     system      total        real       DB<br>preload      3.534913   0.268949   3.803862 (  5.674110)   1.8702<br>eager_load   6.505436   0.418329   6.923765 (  8.598696)   1.6749<br>------------------------------------ total: 10.727627sec<br><br>                 user     system      total        real       DB<br>preload      3.565667   0.264238   3.829905 (  5.779961)   1.9501<br>eager_load   6.667187   0.329823   6.997010 (  8.647524)   1.6505</pre><h4>Gists</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/60fe190a552dd1d205d50594d7b11f00/href">https://medium.com/media/60fe190a552dd1d205d50594d7b11f00/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f5b30989e6cb0fe39f24c92af928ba6/href">https://medium.com/media/6f5b30989e6cb0fe39f24c92af928ba6/href</a></iframe><blockquote><strong>Rem. </strong>In Rails 7.1/8 you shold use to_fs(:human_size) , for earlier 6.1, 7.0 — to_s</blockquote><p>Usage example:</p><pre># random 100 records from Course table with topics and lessons <br># preloading and eager_loading<br>ActiveRecord::Base.logger.silence{ <br>  compare_ram(Course, 100, topics: :lessons)<br>}<br><br># For different rails versions comparison:<br># fixed 100 records from Course table started from id = 1000 <br># with topics and lessons preloading and eager_loading<br>compare_ram(Course.where(id: 1000..).limit(100), 100, topics: :lessons)<br><br># random 100 records from Course table with <br># preloaded topics -&gt; lessons -&gt; homeworks<br># ( course has homework through topics and lessons )<br># and eager_loaded homeworks <br>compare_ram(Course, 100, :homeworks)<br><br># random 100 records from PublicMaterial table with categories<br>ActiveRecord::Base.logger.silence{ <br>  compare_ram(PublicMaterial, 100, :categories) <br>}</pre><h4>Just for the cool preview sake</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*MMB5iVKLGH3VoHCj3jd9HQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe1f10b944a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The battle royal over N+1 in ActiveRecord. Part 1.]]></title>
            <link>https://leshchuk.medium.com/the-battle-royal-over-n-1-in-activerecord-part-1-5ce11870de62?source=rss-afaaebe85f49------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ce11870de62</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[activerecord]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[AlekseyL]]></dc:creator>
            <pubDate>Wed, 25 Jun 2025 06:59:03 GMT</pubDate>
            <atom:updated>2025-07-04T06:42:47.702Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deep dive into eager_load and preload.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*hQlhYd49E78KHpBDKJWkqQ.png" /><figcaption><strong><em>Jakuniku kyoushoku</em></strong></figcaption></figure><p>One of the questions I always ask during an interview is about the N+1 problem and the way you can handle it in a rails project. If an interviewee does not came up with theincludes, then it’s an obvious no go. When passed, comes the next question: what are the real options behind includes, cause includes is a ‘wrapper’ for two completely different approaches: eager_load and preload*.</p><p>And then comes the final question: <strong>how they differ and which one is better?</strong></p><blockquote>*You may consider includes as a declarative, and eager_load and preload as imperative approaches. <em>includes</em> allows ActiveRecord::Relation to decide which one to prefer during record loading process based on the eager_loading?method execution result.</blockquote><blockquote><strong>Disclaimer:</strong> the following is compatible at least with ActiveRecord 6.1.x, 7.0, 8.0.</blockquote><h3>eager_load, one query for all records!</h3><p>This is how it usually works:</p><ul><li>ActiveRecord joins tables of nested collections via left outer join,</li><li>combines WHERE conditions from relations definitions and their default scopes into JOIN ON conditions</li><li>applies other conditions over nested collections via basicWHERE,</li><li>and then aliases ALL column-attributes with technical names to be able to distinct them in a DB response</li><li>finally ActiveRecord populates and stitch together objects with a received data.</li></ul><p>If relations defined like this:</p><pre>class Topic<br>  enum :kind, [:courses, :school]<br>  has_many :lessons<br>end</pre><p>then this simple example:</p><pre><br>Topic.eager_load(:lessons)<br>     .where(lessons: {is_public: false})<br>     .where(kind: :school)</pre><p>will run raw SQL like this:</p><pre> SELECT &quot;topics&quot;.&quot;id&quot; AS t0_r0, &quot;topics&quot;.&quot;title&quot; AS t0_r1, <br>        &quot;topics&quot;.&quot;description&quot; AS t0_r2, <br>        &quot;topics&quot;.&quot;course_id&quot; AS t0_r3, &quot;topics&quot;.&quot;created_at&quot; AS t0_r4, <br>        &quot;topics&quot;.&quot;updated_at&quot; AS t0_r5, &quot;topics&quot;.&quot;partition&quot; AS t0_r6, <br>        &quot;topics&quot;.&quot;position&quot; AS t0_r7, &quot;topics&quot;.&quot;free&quot; AS t0_r8, <br>        &quot;topics&quot;.&quot;deleted_at&quot; AS t0_r9, &quot;topics&quot;.&quot;kind&quot; AS t0_r10, <br>        &quot;topics&quot;.&quot;lessons_count&quot; AS t0_r11, <br>        &quot;lessons&quot;.&quot;id&quot; AS t1_r0, &quot;lessons&quot;.&quot;title&quot; AS t1_r1, <br>        &quot;lessons&quot;.&quot;description&quot; AS t1_r2, &quot;lessons&quot;.&quot;topic_id&quot; AS t1_r3, <br>        &quot;lessons&quot;.&quot;created_at&quot; AS t1_r4, &quot;lessons&quot;.&quot;updated_at&quot; AS t1_r5, <br>        &quot;lessons&quot;.&quot;partition&quot; AS t1_r6, &quot;lessons&quot;.&quot;position&quot; AS t1_r7, <br>        &quot;lessons&quot;.&quot;parent_id&quot; AS t1_r8, &quot;lessons&quot;.&quot;education_year&quot; AS t1_r9, <br>        &quot;lessons&quot;.&quot;text&quot; AS t1_r10, &quot;lessons&quot;.&quot;actived&quot; AS t1_r11, <br>        &quot;lessons&quot;.&quot;is_public&quot; AS t1_r12, &quot;lessons&quot;.&quot;online&quot; AS t1_r13, <br>        &quot;lessons&quot;.&quot;deleted_at&quot; AS t1_r14, &quot;lessons&quot;.&quot;kind&quot; AS t1_r15, <br>        &quot;lessons&quot;.&quot;recording_link&quot; AS t1_r16, &quot;lessons&quot;.&quot;body&quot; AS t1_r17, <br>        &quot;lessons&quot;.&quot;content_updated_at&quot; AS t1_r18<br>  FROM &quot;topics&quot;<br>  LEFT OUTER JOIN &quot;lessons&quot; ON &quot;lessons&quot;.&quot;topic_id&quot; = &quot;topics&quot;.&quot;id&quot;<br>  WHERE &quot;lessons&quot;.&quot;is_public&quot; = TRUE AND &quot;topics&quot;.&quot;kind&quot; = 2</pre><p>There are more then meets the eye here. First of all it’s not actually an OUTER join.</p><h4>eager_load + OUTER JOIN, INNER than you might think</h4><p>Wait a minute, how is this is not an OUTER JOIN it’s right there? Yes and no, there is a difference in results between conditions applied in JOIN VS WHERE.</p><p>Lets compare two simplified SQL queries:</p><pre>SELECT * FROM &quot;topics&quot;<br>  LEFT OUTER JOIN &quot;lessons&quot; ON &quot;lessons&quot;.&quot;topic_id&quot; = &quot;topics&quot;.&quot;id&quot; <br>                           AND &quot;lessons&quot;.&quot;is_public&quot; = TRUE<br>  WHERE &quot;topics&quot;.&quot;kind&quot; = 2</pre><pre>SELECT * FROM &quot;topics&quot;<br>  LEFT OUTER JOIN &quot;lessons&quot; ON &quot;lessons&quot;.&quot;topic_id&quot; = &quot;topics&quot;.&quot;id&quot;<br>  WHERE &quot;lessons&quot;.&quot;is_public&quot; = TRUE AND &quot;topics&quot;.&quot;kind&quot; = 2</pre><p>If you a little bit confused of how those are gonna differ: think of it as one big table of topic_lessons, and whenever topic doesn’t have the corresponding lessons, topic_lesson still present and has all of the lessons columns filled with NULL’s whenever JOIN conditions does not match.</p><p>Now you are ready to apply WHERE on this topic_lessons table.</p><p>In the <strong>first case</strong> we will filter out everytopic_lessons of topics.kind = 2 , disregarding of what is the lessons.is_publicvalue.</p><p>In the <strong>second case</strong>, when topic_lesson does not havelesson part, thetopic_lessons.is_publicequals NULL, hencelessons.is_public = TRUE also equals NULL, so such records will be filtered out from the output.</p><blockquote>If you don&#39;t placeIS NULL condition on the nested relation thenINNER JOIN behaviour and planning will be applied during fetch.</blockquote><p>Why is this matters?</p><blockquote>Because it reveals an opportunity to replace eager_load with preload, and rewrite condition in a form of IN(…) query, whenever this might be reasonable from CPU or RAM perspective.</blockquote><h4>One but not for all</h4><p>The way eager_load prevents N+1 (via JOIN), will inevitably fall into the behaviour you may not expect:</p><p>It will <strong>filter out nested relation </strong>records!</p><p>Let’s look for this example one more time:</p><pre>Topic.eager_load(:lessons)<br>     .where(lessons: {is_public: true})<br>     .where(kind: :courses)</pre><p>For each topic it will eager load <strong>only</strong> thelessons with is_public = true!</p><p>You may say that’s OK and intended and I would like to disagree. I’m reading code as:</p><ul><li>select topics of :courses kind which also have at least one public lesson</li><li>then eager_load their lessons</li></ul><p>You may argue, but lets change the scope to:</p><pre>Topic.eager_load(:lessons)<br>     .where(kind: :courses)<br>     .or(Topic.where(lessons: {is_public: true}))</pre><p>Cleared out SQL will look like this:</p><pre>SELECT &quot;topics&quot;.&quot;*&quot; AS t0_*, ...<br>  &quot;lessons&quot;.&quot;*&quot; AS t1_*, ...<br>  FROM &quot;topics&quot;<br>  LEFT OUTER JOIN &quot;lessons&quot; ON &quot;lessons&quot;.&quot;topic_id&quot; = &quot;topics&quot;.&quot;id&quot;<br>  WHERE &quot;topics&quot;.&quot;kind&quot; = 2 OR &quot;lessons&quot;.&quot;is_public&quot; = TRUE</pre><p>For the topics with lessons lessons.is_public = TRUE and topics.kind &lt;&gt; 2 ActiveRecord will <strong>only load lessons </strong>lessons.is_public = TRUE</p><p>Lets rewrite it in form of includes:</p><pre>Topic.includes(:lessons)<br>   .where(kind: :courses)<br>   .or(Topic.where(lessons: {is_public: true}))</pre><p>Now the behaviour is buried two levels deeper and if you have, lets say a topic of a :school kind with one public and 10 private lessons, eager_load will retrieve only one lesson to the topic.lessons and called it a day.</p><h4>Hell of a LIMIT</h4><p>One more rarely mentioned thing about eager_load — it’s struggling with theLIMITclause. It’s very unusual to work with limitless collections, and eager_loading have a little surprise for you under the hood: it may run two queries instead of one*!</p><pre>Topic.eager_load(:lessons)<br>     .where(lessons: {is_public: true})<br>     .where(kind: :courses)<br>     .limit(10)</pre><p>Will transform into these 2 SQL queries:</p><pre>SELECT DISTINCT &quot;topics&quot;.&quot;id&quot;<br>  FROM &quot;topics&quot;<br>  LEFT OUTER JOIN &quot;lessons&quot; ON &quot;lessons&quot;.&quot;topic_id&quot; = &quot;topics&quot;.&quot;id&quot;<br>  WHERE &quot;lessons&quot;.&quot;is_public&quot; = TRUE AND &quot;topics&quot;.&quot;kind&quot; = 2<br>  LIMIT 10</pre><pre>SELECT &quot;topics&quot;.&quot;*&quot; AS t0_*, <br>        &quot;lessons&quot;.&quot;*&quot; AS t1_*,<br>  FROM &quot;topics&quot;<br>  LEFT OUTER JOIN &quot;lessons&quot; ON &quot;lessons&quot;.&quot;topic_id&quot; = &quot;topics&quot;.&quot;id&quot;<br>  WHERE &quot;lessons&quot;.&quot;is_public&quot; = TRUE AND &quot;topics&quot;.&quot;kind&quot; = 2 <br>       AND &quot;topics&quot;.&quot;id&quot; IN (141, 142, 143, 144, 145, 146, 147, 148, 149, 150)</pre><p>The main reason for that is a performance enhancement: DISTINCT BY idis much cheaper than DISTINCT done by * . In numbers that could be anything, in a simple cases I’ve experienced 4–5 times faster execution:</p><p><a href="https://stackoverflow.com/a/79442915/4495899">Avoiding double query when eager loading Active Record association?</a></p><p>In some rare cases when tables are small with a tiny set of simple attributes, +1 roundtrip may cost a little bit more and DISTINCT * might be faster, but achievement is tiny and the potential for future performance downfall is huge.</p><blockquote>*<strong>Rem.</strong> Two queries happens when eager_load meets has_many relation with LIMIT, has_one or belongs_to both runs in a single query.</blockquote><h4>derailed relation with scopes</h4><p>There is one a potentially bad choice for eager_loading — relation with a scope. What could happened here is a russian roulette, which depends on a scope’s definition.</p><p>Here are two examples, you could try and guess what would potentially go wrong on eager loading:</p><pre># this is just an examples of how things which works fine with a preload, <br># could easily break with an eager_load<br>class Topic<br>  # there isn&#39;t such code in my repos, but its cool as an example<br>  has_one :last_lesson, -&gt; { order(:id).limit(1) }, class_name: :Lesson<br>  # real relation:<br>  has_many :lessons <br>end<br><br>Topic.eager_load(:last_lesson).limit(3)</pre><p>Will run single query like this:</p><pre>SELECT DISTINCT &quot;topics&quot;.&quot;id&quot; AS t0_r0, &quot;topics&quot;.&quot;title&quot; AS t0_r1, ...<br>  &quot;lessons&quot;.&quot;id&quot; AS t1_r0, &quot;lessons&quot;.&quot;title&quot; AS t1_r1,...<br>  FROM &quot;topics&quot;<br>  LEFT OUTER JOIN &quot;lessons&quot; ON &quot;lessons&quot;.&quot;topic_id&quot; = &quot;topics&quot;.&quot;id&quot;<br>  LIMIT 3</pre><p>And amount of loaded topics here is from 1 to 3.</p><p>Because the relation was has_one rails expect underlying data to be one-to-one, hence doing everything in one query, but underlying data is has_many, and should be done with two queries as we saw earlier!</p><p>Another example to break:</p><pre>class Homeworks<br>  # we were lazy here and include ActiveStorage attachments via scope, <br>  # this works cool with ar_lazy_preoload, no need for complex includes<br>  has_many :task_cards, -&gt; { with_attached_media_files }<br>end<br><br>Lesson.eager_load(homework: :task_cards).limit(10) </pre><p>will run SQL like this:</p><pre>SELECT DISTINCT &quot;lessons&quot;.&quot;id&quot; <br>  FROM &quot;lessons&quot; <br>  LEFT OUTER JOIN &quot;homeworks&quot; ON &quot;homeworks&quot;.&quot;lesson_id&quot; = &quot;lessons&quot;.&quot;id&quot; <br>  LEFT OUTER JOIN &quot;task_cards&quot; ON &quot;task_cards&quot;.&quot;resource_type&quot; = &#39;Homework&#39; AND <br>                                 &quot;task_cards&quot;.&quot;resource_id&quot; = &quot;homeworks&quot;.&quot;id&quot; <br>  WHERE &quot;lessons&quot;.&quot;deleted_at&quot; IS NULL LIMIT 10  <br><br>SELECT &quot;lessons&quot;.&quot;id&quot; AS t0_r0, &quot;lessons&quot;.&quot;title&quot; AS t0_r1,...<br>  &quot;homeworks&quot;.&quot;id&quot; AS t1_r0, &quot;homeworks&quot;.&quot;description&quot; AS t1_r1,...<br>  FROM &quot;lessons&quot;<br>  LEFT OUTER JOIN &quot;homeworks&quot; ON &quot;homeworks&quot;.&quot;lesson_id&quot; = &quot;lessons&quot;.&quot;id&quot;<br>  LEFT OUTER JOIN &quot;task_cards&quot; ON &quot;task_cards&quot;.&quot;resource_type&quot; = &#39;Homework&#39; AND<br>                                  &quot;task_cards&quot;.&quot;resource_id&quot; = &quot;homeworks&quot;.&quot;id&quot;<br>  WHERE &quot;lessons&quot;.&quot;id&quot; IN (...)</pre><p>eager_load will not be loading media_files in the same query, and you will fall into N+1 here trying to get them, as for the preload — it’s OK with that kind of a definition.</p><h3>preload, all queries for one purpose!</h3><p>preload is a default approach used by ActiveRecord includes</p><pre>Topic.includes(:lessons).where(kind: :school)</pre><p>Will execute the same way as:</p><pre>Topic.preload(:lessons).where(kind: :school)</pre><p>The basic idea of preloading is to load collections one by one, starting from the root.</p><p>So in this case there will be two queries:</p><pre>SELECT &quot;topics&quot;.*<br>  FROM &quot;topics&quot;<br>  WHERE &quot;topics&quot;.&quot;kind&quot; = 3<br><br>SELECT &quot;lessons&quot;.*<br>  FROM &quot;lessons&quot;<br>  WHERE &quot;lessons&quot;.&quot;deleted_at&quot; IS NULL AND &quot;lessons&quot;.&quot;topic_id&quot; IN (...)</pre><p>Looks pretty easy, but here is the question: how many DB requests needed to preload one relation?</p><p><strong>The right answer:</strong> it depends on the relation definition!</p><h4>‘through’ magic</h4><p>Lets start with through relations:</p><pre>class Course<br>  has_many :topics<br>  has_many :lessons, through: :topics<br>  has_many :homeworks, through: :lessons<br>end</pre><p>And do some preloading:</p><pre>Course.preload(:homeworks).where(kind: :courses).limit(10)</pre><p>And here are the SQL queries:</p><pre>SELECT &quot;courses&quot;.*<br>  FROM &quot;courses&quot;<br>  WHERE &quot;courses&quot;.&quot;kind&quot; = 2 <br>  LIMIT 10<br><br>SELECT &quot;topics&quot;.*<br>  FROM &quot;topics&quot;<br>  WHERE &quot;topics&quot;.&quot;course_id&quot; IN (...)<br><br>SELECT &quot;lessons&quot;.*<br>  FROM &quot;lessons&quot;<br>  WHERE &quot;lessons&quot;.&quot;topic_id&quot; IN (...)<br><br>SELECT &quot;homeworks&quot;.*<br>  FROM &quot;homeworks&quot;<br>  WHERE &quot;homeworks&quot;.&quot;lesson_id&quot; IN (...)</pre><p>That’s +2 queries to preload homeworks, but there is good news: if you refer to course.lessons those are preloaded. Even better, if homework belongs_to lesson with inverse_of, then thelesson will be attached by this preloading process. So you are safe from N+1 in this cases:</p><pre>course.lessons  # already preloaded<br>homework.lesson # inverse_of should be enabled!</pre><p>One more thing to mention ActiveRecord doing an exelent job here, working both ways:</p><pre>Course.preload(topics: {lessons: :homeworks})<br>course.homeworks   # &lt;-- already established during preloading ^<br><br># has same results on preloaded collections as <br>Course.preload(:homeworks)<br>course.lessons   # &lt;-- already established during preloading ^</pre><h4>HABTM me hard</h4><p>Let’s review has and belongs to many relations:</p><pre>class PublicMaterial<br> has_and_belongs_to_many :categories, join_table: :categories_public_materials<br>end<br><br>class Category<br>   has_and_belongs_to_many :public_materials, <br>                           join_table: :categories_public_materials<br>end</pre><p>Then goes simple preloading scope:</p><pre>PublicMaterial.where(is_public: true).preload(:categories).limit(10)</pre><p>Executed queries are:</p><pre>SELECT &quot;public_materials&quot;.*<br>  FROM &quot;public_materials&quot;<br>  WHERE &quot;public_materials&quot;.&quot;is_public&quot; = TRUE<br>  LIMIT 10<br><br>FROM &quot;categories_public_materials&quot;<br>  WHERE &quot;categories_public_materials&quot;.&quot;public_material_id&quot; IN (...)<br><br>SELECT &quot;categories&quot;.*<br>  FROM &quot;categories&quot;<br>  WHERE &quot;categories&quot;.&quot;id&quot; IN (....)</pre><p>This case is actually peculiar because there is no intermediate model for categories_public_materials , and because we are working with an ORM, not raw SQL queries, we need one.</p><p>ActiveRecord will define special private classes for every HABTM relation inside your model classes. Given this example it will be PublicMaterial::HABTM_Categories and Category::HABTM_PublicMaterials</p><h4>Intermediate conclusion</h4><p>So which one is better?</p><p>I don’t like surprises, either they are good or not, and preload is done in a much simpler and straightforward way. The eager_load is quite the opposite, it may come with side effects that are usually unknown to an average developer and surprising for an end user.</p><p>I would prefer preload<strong>,</strong> and my guess is that it’s the same reasoning lying behind the default choice made by ActiveRecord creators.</p><p>But what if the numbers are in favour of eager_load?</p><p>See you in the <a href="https://medium.com/@leshchuk/the-battle-royal-over-n-1-in-activerecord-fe1f10b944a7">Part 2 with numbers</a>.</p><h4>Appendix</h4><p>Something to refer and to read if you’d like:</p><ol><li><a href="https://www.techtarget.com/searchoracle/answer/LEFT-OUTER-JOIN-with-ON-condition-or-WHERE-condition">https://www.techtarget.com/searchoracle/answer/LEFT-OUTER-JOIN-with-ON-condition-or-WHERE-condition</a></li><li><a href="https://sqlbenjamin.wordpress.com/2017/12/23/sql-tip-left-joins-and-where-clauses-are-they-really-left-joins/">https://sqlbenjamin.wordpress.com/2017/12/23/sql-tip-left-joins-and-where-clauses-are-they-really-left-joins/</a></li><li><a href="https://www.bigbinary.com/blog/preload-vs-eager-load-vs-joins-vs-includes">https://www.bigbinary.com/blog/preload-vs-eager-load-vs-joins-vs-includes</a></li><li><a href="https://blog.saeloun.com/2020/01/08/activerecord-database-performance-n-1-includes-preload-eager-load-pluck/">https://blog.saeloun.com/2020/01/08/activerecord-database-performance-n-1-includes-preload-eager-load-pluck/</a></li><li><a href="https://tadhao.medium.com/joins-vs-preload-vs-includes-vs-eager-load-in-rails-5f721c44b3a9">https://tadhao.medium.com/joins-vs-preload-vs-includes-vs-eager-load-in-rails-5f721c44b3a9</a></li><li><a href="https://bhserna.com/includes-preload-eager-load-joins-in-rails">https://bhserna.com/includes-preload-eager-load-joins-in-rails</a></li><li><a href="https://medium.com/@havus.it/understanding-rails-activerecord-preload-eager-load-joins-and-includes-f1122773a25f">https://medium.com/@havus.it/understanding-rails-activerecord-preload-eager-load-joins-and-includes-f1122773a25f</a></li><li><a href="https://stackoverflow.com/questions/68298731/avoiding-double-query-when-eager-loading-active-record-association/79442915#79442915">https://stackoverflow.com/questions/68298731/avoiding-double-query-when-eager-loading-active-record-association/79442915#79442915</a></li><li><a href="https://bhserna.com/when-is-better-to-use-preload-or-eager-load-vs-includes">https://bhserna.com/when-is-better-to-use-preload-or-eager-load-vs-includes</a></li><li><a href="https://bhserna.com/fixing-n-plus-1-queries-can-hurt-performance">https://bhserna.com/fixing-n-plus-1-queries-can-hurt-performance</a></li><li><a href="https://bhserna.com/5-ways-to-fetch-the-latest-n-of-each-record-on-rails">https://bhserna.com/5-ways-to-fetch-the-latest-n-of-each-record-on-rails</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ce11870de62" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[On the IN-side]]></title>
            <link>https://leshchuk.medium.com/on-the-in-side-7b6625a8223e?source=rss-afaaebe85f49------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b6625a8223e</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[AlekseyL]]></dc:creator>
            <pubDate>Thu, 05 Jun 2025 12:57:35 GMT</pubDate>
            <atom:updated>2025-06-06T10:57:00.292Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>How I Learned to Stop Worrying and Love the IN-queries</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bVOwOnppQrcjVVRhtjs1aw.png" /><figcaption>IN(…) will now throw some punches back!</figcaption></figure><p>Recently I’ve read the article <a href="https://andyatkinson.com/big-problems-big-in-clauses-postgresql-ruby-on-rails">https://andyatkinson.com/big-problems-big-in-clauses-postgresql-ruby-on-rails</a>, and I want to throw some hard criticism punches over it.</p><blockquote><strong>Technical disclamer</strong>: I’m running queries against real-life production DB running Postgres-15, and using ActiveRecord as ORM.</blockquote><h4>Did I saw a filter?</h4><p>First of all there were no real-life or synthetic examples with any query plan provided, zero. How can you say this is bigger/smaller or faster/slower when you are not providing numbers?</p><p>Article states:</p><blockquote>We’ll refer to this pattern as “Big INs,” which are queries with an IN clause that has a big list of values. As data grows, the length of the list of values will grow. These queries tend to perform poorly for big lists, causing user experience problems or <strong>even partial outages.</strong></blockquote><p>Technically speaking I can imagine millions items inside IN stabbing postgres-planner in the back, but on the million-size scale you can outage you DB with any clause.</p><blockquote>We’ll dig into the origins of this pattern, why the performance of it is poor, and explore some alternatives that you can use in your projects..</blockquote><blockquote>For example in the SQL query below, the IN clause portion is WHERE author_id IN (1,2,3) and the list of scalar expressions is (1,2,3).</blockquote><blockquote>SELECT * FROM books WHERE author_id IN (1, 2, 3);</blockquote><blockquote>The purpose of this clause is to perform filtering. Looking at a query execution plan in Postgres, we’ll see something like this fragment below:</blockquote><blockquote>Filter: (author_id = ANY (&#39;{1,2,3}&#39;::integer[]))</blockquote><blockquote>This of course filters the full set of books down to ones that match on author_id.</blockquote><blockquote>Filtering is a typical database operation. Why are these slow?</blockquote><p>Can’t you see a real issue here?</p><blockquote><strong><em>Filter:</em></strong><em> (author_id = ANY (&#39;{1,2,3}&#39;::integer[]))</em></blockquote><p>If you have index over author_id, which you should, since it’s a foreign key column, than with a query like this:</p><pre>SELECT &quot;lesson_sessions&quot;.* <br>  FROM &quot;lesson_sessions&quot; <br>  WHERE &quot;lesson_sessions&quot;.&quot;lesson_id&quot; IN (4520,33687,21378)</pre><p>your plan will look something like this:</p><pre>------------------------------------------------------------------------------------------------------------------------------------------------------------<br> Index Scan using index_lesson_sessions_on_lesson_id on lesson_sessions  (cost=0.43..914.06 rows=1031 width=379) (actual time=0.030..0.251 rows=77 loops=1)<br>   Index Cond: (lesson_id = ANY (&#39;{4520,33687,21378}&#39;::bigint[]))<br> Planning Time: 0.229 ms<br> Execution Time: 0.295 ms</pre><p>Let me make it bold:</p><p><strong>Index Cond:</strong> (lesson_id = ANY (‘{4520,33687,21378}’::bigint[]))</p><p>Yes, filtering can screw you in any way possible, but it’s not an IN here is the cause. And yes, sometimes it could boil down to filter even over pkey column, but what are the real chances? Requesting half of a pkeys? More selective index alongside, more selective than pkey, really?</p><p>My point here: <strong>Filter:</strong> (foreign_id = ANY (&#39;{1,2,3}&#39;::integer[])) is a bad example, which is hard to find when querying indexed columns.</p><h4>Lets talk numbers</h4><blockquote>Remember that our queries are parsed, planned, and executed. A big list of values are treated like constants, and don’t have associated statistics.</blockquote><blockquote>Queries with big lists of values take more time to parse and use more memory.</blockquote><p>OK, it definitely takes more time to parse and plan, but can I see numbers here?</p><p>Cause I can show some: planning of <strong>+1K</strong> of ids for INquery<strong> costs +0.6ms</strong> for planner-time on a 8.4M records table under &lt; 65K elements provided toINclause, and <strong>+1.2ms</strong> after reaching 65K or more. Samish numbers I’ve got for 4M records table so looks like its a relevant measuring.</p><p>Anyway how bad is this? This bad*:</p><pre># LessonSession.count ~ 8.4M<br>ids = LessonSession.ids<br><br>LessonSession.where(id: ids.sample(10_000)).explain(:analyze)<br><br>ActiveRecord::Base.logger.silence do <br> Benchmark.bm do |bm| <br>   bm.report{ LessonSession.where(id: ids.sample(10_000)).to_a }<br>   bm.report{ LessonSession.where(id: ids.sample(10_000)).each(&amp;:as_json) }<br> end<br>end</pre><pre>100_000 records, to_a ---------------------------------------------------<br>    user   system    total       real<br>1.457796 0.122168 1.579964 ( 2.343037)<br>                             0.390134  - 16.6% data prepare and trasfer<br>                             0.372939  - 15.9% execution + planning<br>                             0.106236  - 4.5% spent in DB planning  &lt;---<br>50_000 records, to_a ---------------------------------------------------<br>    user   system    total       real<br>0.955977 0.041487 0.997464 ( 1.417798)<br>                             0.18388   - 12.9% data prepare and trasfer<br>                             0.236453  - 16.7% execution + planning<br>                             0.032863  - 2.3% spent in DB planning  &lt;---<br><br>10_000 records, to_a ---------------------------------------------------<br>    user   system     total        real<br>0.196055 0.018941  0.214996 ( 0.315378)<br>                              0.048531 - 15.3% data prepare and trasfer<br>                              0.051851 - 16.4% execution + planning<br>                              0.004867 - 1.5% spent in DB planning  &lt;---<br><br>10_000 records, as_json ------------------------------------------------<br>    user    system     total      real<br>2.809430 0.102656  2.912086 ( 2.997389) <br>                              0.004867 - 0.15% spent in DB planning  &lt;---</pre><p>I’ll leave it up to you to decide how bad this actually is…</p><blockquote>*I’m running PG-15 so there is no memory option for explain, may be someday later.</blockquote><p>So, lets continue with the following:</p><blockquote>Without pre-collected table statistics for planning decisions, PostgreSQL is more likely to mis-estimate cardinality and row selectivity.</blockquote><blockquote>This can mean the planner chooses a sequential scan over an index scan, causing a big slowdown.</blockquote><p>Let me clear this out, despite that inside IN(?) could be anything, implicitly author is talking about pkey IN(…) OR foreign_key IN(…) for relations preloading.</p><p>So let’s be explicit:</p><blockquote><strong>N+1 eager loading/preloading is the one and only reason you are facing big INs</strong></blockquote><p>There is no other common real-life example, at least I can’t recall it. Yes you can do some madness, and create some hideous INquery, just to prove me wrong, but that would be the opposite: an exception that proves the rule — it’s two orders of magnitude more uncommon than N+1 issue done by ORM.</p><p>Under this circumstanses we should assume that <strong>we always have some kind of an index for elements under</strong>IN<strong>clause. </strong>This means that posgtres planner will have zero issues with the selectivity and cardinality on pkey and foreign_key columns.</p><p>OK, lets move on.</p><blockquote>Active Record ORM creating this pattern implicitly</blockquote><blockquote>This query pattern can happen when using eager loading methods like includes or preload.</blockquote><blockquote>This <a href="https://www.crunchydata.com/blog/real-world-performance-gains-with-postgres-17-btree-bulk-scans">Crunchy Data post</a> mentions how eager loading methods produce IN clause SQL queries.</blockquote><blockquote>The post links to the <a href="https://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations">Eager Loading Associations documentation</a> which has examples in Active Record and the resulting SQL that we’ll use here.</blockquote><blockquote>Let’s first discuss N+1 with these examples.</blockquote><blockquote>Fixing N+1s</blockquote><blockquote>Let’s study the examples here. Here’s some Active Record for books and authors:</blockquote><blockquote># N+1<br>books = Book.limit(10)</blockquote><blockquote>books.each do |book|<br> puts book.author.last_name<br>end</blockquote><blockquote>The issue above is the undesirable N+1 query pattern, where a table is repeatedly queried in a loop, instead of bulk loading a set of rows.</blockquote><blockquote>To fix the N+1, we’ll add the includes(:author) eager loading method to the code above.</blockquote><blockquote>That looks like this:</blockquote><blockquote>books = Book.includes(:author).limit(10) 👈</blockquote><blockquote>books.each do |book|<br> puts book.author.last_name<br>end</blockquote><blockquote>We’ve now eliminated the N+1 queries, but we’ve opened ourselves up to a new possible problem.</blockquote><p>Nope we didn’t.</p><blockquote>Eager loading with includes or preload</blockquote><blockquote>While the includes(:author) fixed the N+1 queries, Active Record is now creating two queries, with the second one having an IN clause.</blockquote><blockquote>Here’s the example from above as SQL:</blockquote><blockquote>SELECT books.* FROM books LIMIT 10;</blockquote><blockquote>SELECT authors.* FROM authors<br> WHERE authors.id IN (1,2,3,4,5,6,7,8,9,10);</blockquote><blockquote>Here we only have 10 values for the IN clause, so performance will be fine. However, <strong>once we’ve got hundreds or thousands of values, we will run into the problems described above.</strong></blockquote><blockquote>Performance will tank if the authors.id primary key index isn’t used for this filtering operation.</blockquote><blockquote>Where else do these IN clause queries come from?</blockquote><p>How many thousands are we talking here? Can this statement be more specific? Cause I can:</p><blockquote>For 10K records only 10% of DB execution time will be spent in plannig, and on the scale of just getting 10K and running as_json for each record the planning time would be 0.15%<strong> of total time!</strong></blockquote><p>I can’t even imagine how small this thing is from the end-user perspective, how long it would take to transfer such amount of data, render in browser e.t.c compared to DB-planning, three-four order of magnitude?</p><h4>eager_load eventually suck</h4><blockquote>Eager loading using eager_load</blockquote><blockquote>Besides includes() and preload() which create two queries with the second having an IN clause, there’s another way to do eager loading in Active Record.</blockquote><blockquote>An alternative method eager_load works a little bit differently. It produces a single SQL query that uses a LEFT OUTER JOIN.</blockquote><blockquote>Here’s an example of eager_load from the Active Record documentation:</blockquote><blockquote>books = Book.eager_load(:author).limit(10)</blockquote><blockquote>books.each do |book|<br> puts book.author.last_name<br>end</blockquote><blockquote>The following single SQL query is produced. Note that it has no IN clause.</blockquote><blockquote>SELECT<br> &quot;books&quot;.&quot;id&quot; AS t0_r0,<br> &quot;books&quot;.&quot;title&quot; AS t0_r1<br>FROM<br> &quot;books&quot; LEFT OUTER JOIN &quot;authors&quot;<br> ON &quot;authors&quot;.&quot;id&quot; = &quot;books&quot;.&quot;author_id&quot;<br>LIMIT 10;</blockquote><blockquote>Since we’re now using a join operation, we’ve got statistics available from both tables. This makes it much more likely PostgreSQL can correctly estimate selectivity and cardinality.</blockquote><blockquote>The planner also isn’t needing to parse and store a large list of constant values.</blockquote><blockquote>While IN clauses might perform fine with smaller inputs, e.g. 100 values or fewer,<a href="https://andyatkinson.com/big-problems-big-in-clauses-postgresql-ruby-on-rails#fn:1">1</a> for large lists we should try and restructure the query to use a join operation instead.</blockquote><blockquote>Besides restructuring the queries into joins, are there other alternatives?</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=%2F%2Fcoub.com%2Fembed%2Fgorlia%3Fmaxheight%3D360%26maxwidth%3D640&amp;display_name=Coub&amp;url=https%3A%2F%2Fcoub.com%2Fview%2Fgorlia&amp;image=https%3A%2F%2Fattachments-cdn-s.coub.com%2Fcoub_storage%2Fcoub%2Fsimple%2Fcw_image%2F2585833b4ac%2F335aa44d8e0b97a6dd223%2Fbig_1673107156_1cgzvnu_1446916178_00032.jpg&amp;type=text%2Fhtml&amp;schema=coub" width="640" height="360" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd4af9c166df6c0c885a0559f4f294c3/href">https://medium.com/media/dd4af9c166df6c0c885a0559f4f294c3/href</a></iframe><p>First of all eager_load really sucks in a real-life.* How this even possible? Let me quote myself couple times here.</p><p>From upcoming article <strong>The battle royal over N+1 in ActiveRecord</strong>. <em>Part 2. Numbers</em>:</p><p>Despite the fact thateager_load <em>sometimes</em> run less queries, overhead for the JOIN and bigger raw dataset is noticeble enough even on a DB level so eager_load* <strong>is faster only on a small dataset with nesting around 2 relations deep</strong>. For big enough dataset, in my case starting somewhere around 15 root elements, it’s faster for preload to go to DB couple times more, than have enormous JOIN and return everything in one piece. Again this only DB numbers I’m talking here, cause full times comparision is killing eager_load.</p><p><strong>eager_load looses every contest here</strong>, skipinng couple roundtrips to DB only slightly affect the total ratio, but the complexity of the multiple JOIN&#39;s and result parsing and assignment from raw DB data to an ORM representation is so huge, so couple ms for a roundtrip comes unnoticable!</p><p>In end-to-end numbers: starting from x1.15 loss, for the 10 elements 2-level deep collections, which is optimal for eager_load, ends up <strong>2 times slower for bigger collection</strong> and deeper nesting.</p><p>Reffering the <strong>stackoverflow answer:</strong></p><p>It’s usually kinda dropped out of sight that eager_load with aLIMIT clause <strong>is running two queries</strong>, not one! Cause when you are joining — you’ll have doubles, so to be able to apply LIMIT on the root records you need some DISTINCT over them, and DISTINCT t.* couple times slower than running two requests DISTINCT t.id + SELECT IN(...)</p><p><a href="https://stackoverflow.com/questions/68298731/avoiding-double-query-when-eager-loading-active-record-association/79442915#79442915">https://stackoverflow.com/questions/68298731/avoiding-double-query-when-eager-loading-active-record-association/79442915#79442915</a></p><p>Can you see some irony here? eager_load uses IN(…) under the hood to squeeze some performance from poor JOIN’s…</p><p><em>*Combined with </em>LIMIT<em>, if you running eager_load without </em>LIMIT<em>, it could sometimes be faster, but you’ll pay in RAM for that</em>.</p><h4>ANY?</h4><blockquote>Alternative approaches using ANY or SOME</blockquote><blockquote>Crunchy Data’s post <a href="https://www.crunchydata.com/blog/postgres-query-boost-using-any-instead-of-in">Postgres Query Boost: Using ANY Instead of IN</a> describes how IN is more restrictive on the input.</blockquote><p>No it’s not. Crunchy Data guys does not have an ORM good enough to do IN clause out of the box, that’s why they are suffering. Let’s not mix and match SQL query performance and ORM problems here.</p><p>If you need to compare IN and ANY on the Postgres level here you go:</p><p><a href="https://stackoverflow.com/questions/31191507/how-to-use-any-instead-of-in-in-a-where-clause/31192557#31192557">https://stackoverflow.com/questions/31191507/how-to-use-any-instead-of-in-in-a-where-clause/31192557#31192557</a></p><p><a href="https://stackoverflow.com/a/34627688/4495899">https://stackoverflow.com/a/34627688/4495899</a></p><p>Let me explicitly quote:</p><blockquote>ANY is a later, more versatile addition, it can be combined with any binary operator returning a boolean value. IN<strong> burns down to a special case of</strong> ANY. In fact, its second form is rewritten internally:</blockquote><blockquote>IN<strong> is rewritten with</strong> = ANY<br>NOT IN is rewritten with &lt;&gt; ALL</blockquote><p>So internally there no difference which operator to use.</p><blockquote>A more usable to IN can be using ANY or SOME, which has more flexibility in handling the list of values.</blockquote><blockquote>…</blockquote><blockquote>However, ANY is not generated by Active Record. What if we want to generate these queries using Active Record?</blockquote><blockquote>One option is to use the any method provided by the <a href="https://github.com/GeorgeKaraszi/ActiveRecordExtended">ActiveRecordExtended</a> gem.</blockquote><p>OK. Still I don’t see why ActiveRecord should switch to ANY, really. It’s doing fine with IN.</p><h4>VALUES + JOIN</h4><blockquote>A VALUES clause + A temporary table of ids</blockquote><p>This could be legit advice, even <a href="https://dba.stackexchange.com/users/3684/erwin-brandstetter">Erwin Brandstetter</a> mentioned those:</p><p><a href="https://dba.stackexchange.com/questions/91247/optimizing-a-postgres-query-with-a-large-in/91539#91539">https://dba.stackexchange.com/questions/91247/optimizing-a-postgres-query-with-a-large-in/91539#91539</a></p><p>And he also referenced: <a href="https://postgres.cz/wiki/PostgreSQL_SQL_Tricks_I#Predicate_IN_optimalization">Predicate_IN_optimalization</a></p><p>But this things 10 years old at least, and can somebody show the real measurements here on an end-user scale?</p><h4>Conclusion</h4><blockquote>Conclusion</blockquote><blockquote>In this post, we looked at a problematic query pattern, big IN lists. You may have instances of this pattern in your codebase from direct means or from using some ORM methods.</blockquote><blockquote>This type of query performs poorly for big lists of values, as they take more resources to parse, plan, and execute. There are fewer indexing options compared with an alternative structured as a join operation. Join queries provide two sets of table statistics from both tables being joined, that help with query planning.</blockquote><p>Dear readers, please do not ever replace ligit preload IN(...) queries with any kinds of JOIN. No statistic could save you from an illegit misplaced JOIN.</p><p>I had a real-life case when unnecessary JOIN of already joined table, slowed down the query x500 times, five freaking hundreds times slower!</p><p>I would not belive myself that this is even possible: to double already existing JOIN on a query and to slow the query down x500 times. ( <em>clap if you want to read about this :)) </em>)!</p><blockquote>We learned how to find instances of these using pg_stat_statements for PostgreSQL. The post then considers several alternatives.</blockquote><blockquote>Our main tactics are to convert these queries to joins when possible. Outside of that, we could consider using the ANY operator with an array of values, a VALUES clause, and consider using a prepared statement.</blockquote><blockquote>The next time you see big IN lists causing database performance problems, hopefully you feel more prepared to restructure and optimize them!</blockquote><blockquote>Thanks for reading this post. I’d love to hear about any tips or tricks you have for these types of queries!</blockquote><p>Yea, I have one tip and trick for dealing with those big evilIN queries:</p><blockquote>Just stop worrying and love that ORM producing IN(?) queries under the hood!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b6625a8223e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Delegated UNIQUENESS in Postgres]]></title>
            <link>https://leshchuk.medium.com/delegated-uniqueness-in-postgres-d0fa103f749c?source=rss-afaaebe85f49------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0fa103f749c</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[postgres]]></category>
            <dc:creator><![CDATA[AlekseyL]]></dc:creator>
            <pubDate>Tue, 21 Dec 2021 12:44:15 GMT</pubDate>
            <atom:updated>2021-12-22T06:51:58.480Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wW1stRZFuNgP2oJvFopAyg.png" /><figcaption>Second helper-table might not that shiny but still uniq <a href="https://www.reddit.com/user/Xanice/">© u/Xanice</a></figcaption></figure><h4>What’s inside</h4><ul><li>Multiple approaches to objects ‘optimistic’ creation</li><li>Delegating UNIQUE constraints to a helper table using uuid VS text column types.</li><li>Playing HOT and ‘cold’ on UPDATE requests</li><li>INSERT or UPDATE — should you pay 1 to save 14?</li></ul><h4>Uniqueness flavours</h4><p>Uniqueness is a usual feature for an application and business logic to have. I want to separate some handy flavours of a uniqueness:</p><ul><li><strong>mutable uniqueness: </strong>a uniqueness which should be enforced against updateable column, for instance a changeable user nickname.</li><li><strong>immutable uniqueness: </strong>a uniqueness applied against immutable column. For instance a registration with an email, it should be unique across all users, and let say user cannot change it after. So a backend needs to apply unique constrant <strong>only once</strong>: during record creation.</li><li><strong>short term uniqueness: </strong>a uniqueness applied only for a limited ‘sliding’ subset data, usually the latest records. For instance, <strong>optimistic objects creation resolving a race condition </strong>on a back-end. Let say you have a mobile application with an ability to create some kind of objects without being online ( even being online, but retrying after unexpected failure ). User definitely doesn’t want to experience a multiple entities creation whenever network or service hiccups, that is definitely a bad UX you want to avoid. So back-end needs some kind of uuid based uniqueness at least for a short time period, untill the user application gets a confirmation and the pkey id of a freshly created record.</li></ul><blockquote><strong>Rem. </strong>All of these flavours could be defined without strict conditions, but with some weights numbers. For instance, we can allow updates but the ratio between create and update operations is so small that we actually facing ‘immutable uniqueness’ case, rather than normal ‘mutable’ uniqueness. And a ‘short term uniqueness’ is like a ‘create-only uniqueness’ but over a limited set of last N records.</blockquote><h4>Unique index</h4><p>The easiest way to handle uniqueness over an attribute or a combination of attributes is to introduce a <strong>unique index</strong> over them.</p><p>Any blazing fast triggers-based check or not so blazing fast ORM validation callback cannot deliver 100% solid uniqueness guarantee, because ORM or trigger validation could fall into the race condition.</p><p>But adding an index comes with a price:<strong> its slows updates and insertions</strong>, the more indexes you add — the <a href="https://use-the-index-luke.com/sql/dml/insert#fig_insert">slower insert and update will become</a>, even adding 1 index can cost you <a href="https://postgres.ai/blog/20211029-how-partial-and-covering-indexes-affect-update-performance-in-postgresql#lessons-learned">~40% UPDATEs tps performance</a>.</p><h4>The best UPDATE performance you can get</h4><p>Postgres has one cool performance booster for UPDATE operations, it’s a <a href="https://www.cybertec-postgresql.com/en/hot-updates-in-postgresql-for-better-performance/">heap-only tuples update</a>. There are two conditions for HOT updates to be used:</p><ul><li><strong>there must be enough space</strong> in the block containing the updated row</li><li><strong>there is no index defined on any column whose value is modified</strong></li></ul><p>The later refers not only to the values of indexed columns but also the conditional <a href="https://github.com/postgres/postgres/blob/master/src/backend/access/heap/README.HOT#L34">columns for partial indexes</a>:</p><blockquote>HOT solves this problem for a restricted but useful special case: where a tuple is repeatedly updated in ways that do not change its indexed columns. (Here, “indexed column” <strong>means any column referenced at all in an index definition</strong>, including for example columns that are tested in a partial-index predicate but are not stored in the index.)</blockquote><p>UPDATE operation performance in Postgres follows the HOT-updates ratio, the higher it is, the faster your UPDATEs will be, and vice-versa, lower HOT-updates ratio — slower the UPDATEs.</p><p>So the idea of the speeding up UPDATEs is simple:</p><ul><li>do it HOT if you can</li><li><strong>have lesser indexes whenever it’s not-HOT</strong></li></ul><h4>Delegated uniqueness, the idea</h4><p>If we don’t have a normal mutable uniqueness demand, but ‘immutable’ or ‘short-term’ uniqueness cases, we can <strong>extract the unique condition to an external helper table with an unique index over extracted values</strong>. We can do this using a trigger executed during an INSERT operation on an original table. In other words we are <strong>delegating the unique constraint to the helper-table </strong>and its unique index*.</p><p>In terms of unique constraints this approach works the same way unique index over original table would do, but we can <strong>skip unique index UPDATE</strong>s via trigger conditions, because for our special uniqueness cases we will hit the trigger only on INSERT operation.</p><blockquote><strong>Rem.</strong> This approach could be applied not only to unique indexes of course. You could delegate append-only indexes externally if you want to boost non-HOT UPDATEs, but this idea would need some other math and justification to be done.</blockquote><h4>The experiment</h4><p>I’m gonna measure two kinds of triggers vs indexes: two elements array transform to string + text index, and direct insert of uuid + uuid index.</p><ul><li>I’ll measure INSERT overhead of the different triggers calls VS unique indexes over the same data in place</li><li>I’ll measure costs for non-HOT updates for base table configuration and for +1 unique index of text and uuid types</li></ul><blockquote><strong>Rem. </strong>I’ll use schema from my original project with a partially filled data.</blockquote><h4>Base table configuration stats</h4><ul><li>4M records splitted 50/50 between dialogs and multi-user chats</li><li>1 int64 pkey index</li><li>1 non-pkey index over int64 column</li><li>table fillfactor is 70%</li><li>average record size 830 bytes, max 2077, min 360 ( so its a ~7 records per page )</li><li><strong>PostgreSQL v11.13</strong></li></ul><h4>Text type uniqueness example: unique dialog between two users</h4><p>Any messenger like whatsup or telegram with dialogs and multi-user chats should apply unique constraint for direct messaging chats a.k.a. dialogs.</p><p>The original table has an array column user_ids for storing participants ids. For records with type ‘Dialog’ user_ids will have only two ids for which we need to ensure uniqueness across all records of ‘Dialog’ type.</p><p>This constraint prevents a situation whenever two user starting direct messaging at the same time and end up with two direct-chats created in parallel.</p><p>Here is a schema for the delegated uniqueness trial:</p><pre>-- &#39;two elements array to string&#39; deterministic conversion function <strong><br>CREATE OR REPLACE FUNCTION</strong> <em>user_ids_to_str</em>( user_ids anyarray ) <strong>RETURNS</strong> text <strong>AS</strong> $$<br>   <strong>BEGIN</strong><br>        <strong>RETURN CASE WHEN</strong>( user_ids[1] &gt; user_ids[2]) <br>          <strong>THEN</strong> user_ids[1]::text || &#39;_&#39; || user_ids[2]::text <br>          <strong>ELSE</strong> user_ids[2]::text || &#39;_&#39; || user_ids[1]::text <strong>END</strong>;<br>    <strong>END</strong><br>$$ <strong>LANGUAGE</strong> plpgSQL;<br></pre><pre>-- <em>Helper table schema. No pkey, only one text column + unique index</em><br><strong>CREATE TABLE</strong> dialog_uniqs ( uniq_str text );</pre><pre><strong>CREATE UNIQUE INDEX</strong> index_dialog_uniqs_on_uuid <strong>ON</strong> dialog_uniqs <br>  USING btree (uniq_str);</pre><pre>-- a trigger function to &#39;delegate&#39; uniq constraint to the helper table</pre><pre><strong>CREATE OR REPLACE FUNCTION</strong> dlg_uniqs_trg() <strong>RETURNS</strong> trigger <strong>AS</strong> $$<br><strong>BEGIN <br>  INSERT INTO </strong>dialog_uniqs <strong>VALUES</strong> ( <em>user_ids_to_str</em>(NEW.user_ids) );<br>  <strong>RETURN NEW</strong>;<br><strong>END $$ LANGUAGE</strong> plpgSQL;</pre><pre><strong>CREATE TRIGGER </strong>dlg_uniqs_trg <strong>BEFORE INSERT ON</strong> chats <br>  <strong>FOR EACH ROW WHEN</strong>( NEW.type = &#39;Dialog&#39; )<br>  <strong>EXECUTE FUNCTION</strong> dlg_uniqs_trg();</pre><pre>-- an index for dialogs uniqueness </pre><pre><strong>CREATE UNIQUE INDEX IF NOT EXISTS</strong> dlg_user_ids_index <br>  <strong>ON</strong> chats <strong>USING</strong> btree(<em>user_ids_to_str</em>(user_ids)) <br>  <strong>WHERE</strong>( type=&#39;Dialog&#39; );</pre><h4>uuid type example: optimistic singleton creation</h4><p>‘Optimistic’ entities creation, whenever front-end creates an object first, and then tries to create it using api. The simplest way to eliminate double objects creation on the race condition and map ‘optimistic’ local objects with created ones is to use uuid’s and apply ‘short-term’ or ‘imutable’ uniqueness across front-end generated uuids on the backend side.</p><p>Schema for uuid-type based uniqueness:</p><pre>-- <em>Schema for helper table. No pkey, only one uuid-type column</em><br><strong>CREATE TABLE</strong> chat_uuids ( uuid uuid );</pre><pre><strong>CREATE UNIQUE INDEX</strong> index_dialog_uniqs_on_uuid <strong>ON</strong> chat_uuids <br>  USING btree (uuid);</pre><pre><strong>CREATE OR REPLACE FUNCTION</strong> <em>cht_uuid_trg</em>() <strong>RETURNS</strong> trigger <strong>AS</strong> $$<br><strong>BEGIN <br>  INSERT INTO </strong>chat_uuids <strong>VALUES</strong> ( NEW.uuid );<br>  <strong>RETURN NEW</strong>;<br><strong>END $$ LANGUAGE</strong> plpgSQL;<br><br><strong>CREATE TRIGGER </strong><em>dlg_uuid_trg</em> <strong>BEFORE INSERT ON</strong> chats <br>  <strong>FOR EACH ROW WHEN</strong>( NEW.type = &#39;Dialog&#39; )<br>  <strong>EXECUTE FUNCTION</strong> cht_uuid_trg();</pre><pre>-- this an index for optimistic record creation uniqueness <br>-- partial condition added just to have comparable performance stats between uuid and text indexes</pre><pre><strong>CREATE INDEX </strong>chats_uuid_index <strong>ON</strong> chats <strong>USING</strong> btree(uuid) <strong>WHERE</strong>( type=&#39;Dialog&#39; );</pre><h4><strong>INSERT-numbers</strong></h4><p>Base configuration (2 x int64 indexes), 100 records* inserts ~ <strong>3.5ms on average</strong></p><pre>Insert on chats  (cost=0.00..1.50 rows=100 width=380) (actual time=4.029..4.053 rows=0 loops=1)</pre><pre>-&gt;  Values Scan on &quot;*VALUES*&quot;  (cost=0.00..1.50 rows=100 width=380) (actual time=0.027..1.790 rows=100 loops=1)</pre><pre>Planning Time: 0.515 ms</pre><pre><strong>Execution Time: 4.170 ms</strong></pre><blockquote><strong>Rem</strong> *The <strong>100 records set </strong>delivers a more or less stable UPDATE trials. Running 1K records set trial multiple times in a row to get an average, can easily put all results under a heavy cache influence on 4+M data set.</blockquote><p>Base configuration +<strong> 1 <em>chats_uuid_index</em> index</strong>, 100 records inserts <strong>~4.7ms on average</strong>.</p><pre>Insert on chats  (cost=0.00..1.50 rows=100 width=380) (actual time=4.659..4.684 rows=0 loops=1)</pre><pre>-&gt;  Values Scan on &quot;*VALUES*&quot;  (cost=0.00..1.50 rows=100 width=380) (actual time=0.027..1.919 rows=100 loops=1)</pre><pre>Planning Time: 0.516 ms</pre><pre><strong>Execution Time: 4.748 ms</strong></pre><p>Base configuration +<strong> 1 <em>dlg_user_ids_index</em>* text index</strong>, 100 records inserts <strong>~5.5ms on average</strong>:</p><pre>Insert on chats  (cost=0.00..1.50 rows=100 width=380) (actual time=5.729..5.752 rows=0 loops=1)</pre><pre>-&gt;  Values Scan on &quot;*VALUES*&quot;  (cost=0.00..1.50 rows=100 width=380) (actual time=0.028..1.889 rows=100 loops=1)</pre><pre>Planning Time: 0.546 ms</pre><pre><strong>Execution Time: 5.820 ms</strong></pre><blockquote>*Look for dlg_user_ids_index definition, to the index specifics.</blockquote><p>Base configuration + a simple uuid transition trigger and a helper table, 100 inserts in one request <strong>~7.9ms on average</strong>:</p><pre>Insert on chats  (cost=0.00..1.50 rows=100 width=380) (actual time=8.475..8.498 rows=0 loops=1)</pre><pre>-&gt;  Values Scan on &quot;*VALUES*&quot;  (cost=0.00..1.50 rows=100 width=380) (actual time=0.027..1.829 rows=100 loops=1)</pre><pre>Planning Time: 0.565 ms</pre><pre><strong>Trigger dlg_uuids_trg: time=3.510 calls=100</strong></pre><pre><strong>Execution Time: 8.563 ms</strong></pre><p>Base configuration + a ‘complex’ trigger with a conversion and a helper table, 0.1K inserts in one request is <strong>~8.4ms on average</strong>:</p><pre>Insert on chats  (cost=0.00..1.50 rows=100 width=380) (actual time=8.930..8.952 rows=0 loops=1)</pre><pre>-&gt;  Values Scan on &quot;*VALUES*&quot;  (cost=0.00..1.50 rows=100 width=380) (actual time=0.027..1.779 rows=100 loops=1)</pre><pre>Planning Time: 0.507 ms</pre><pre><strong>Trigger dialog_uniqs_trg: time=4.126 calls=100</strong></pre><pre><strong>Execution Time: 9.014 ms</strong></pre><p>Pay attention to this execution plan parts timings:</p><pre>-- two elems array transform to a string trigger time:<strong><br>Trigger dialog_uniqs_trg: time=4.126 calls=100</strong></pre><pre>-- uuid insert trigger without any manipulation: <strong><br>Trigger dlg_uuids_trg: time=3.510 calls=100</strong></pre><p>You can see the real timing of the added <strong>triggers ~0.03-0.04ms per one execution*</strong>, so you can get some valuable hint on the overheads.</p><p><strong><em>*</em></strong><em>This timmings depends on amount of records to be inserted in a query, 1K inserts shows a little bit faster executions: (Trigger </em><strong><em>dialog_uniqs_trg</em></strong><em>: time=</em><strong><em>34.242</em></strong><em> calls=1000 / Trigger </em><strong><em>dlg_uuids_trg</em></strong><em>: time=</em><strong><em>28.092</em></strong><em> calls=1000</em><strong><em> </em></strong><em>)</em></p><blockquote><strong>Rem.</strong> For <strong>truncated helper-table</strong> insertion trigger executes <strong>x1.2 times faster on a 2M scale</strong>, this could be considered as an optimization for ‘short-term’ uniqueness, but it should be done with caution.</blockquote><p><strong>UPDATE</strong></p><p>In contrast to INSERT, UPDATE operation is very sensitive to the state of a Postgres cache. Numbers are bouncing a lot, so to eliminate cache factor I’m averaging series of 10 requests of 100 record updates couple of times, and in between doing some dummy full scan request against table, like COUNT, MIN, MAX, AVG, creating/dropping indexes e.t.c.. This makes result more or less predictable and measurable.</p><p>1–2 indexes, <strong>HOT update</strong> of 100 records, average time~<strong>11ms</strong>:</p><pre>Update on spaces  (cost=0.43..843.49 rows=100 width=656) (actual time=10.962..10.979 rows=0 loops=1)</pre><pre>-&gt;  Index Scan using spaces_pkey on spaces  (cost=0.43..843.49 rows=100 width=656) (actual time=0.049..9.297 rows=100 loops=1)</pre><pre>Index Cond: (id = ANY (&#39;{5375068,1547543,...}&#39;::bigint[]))</pre><pre>Planning Time: 0.203 ms</pre><pre><strong>Execution Time: 11.024 ms</strong></pre><p>Base configuration, 100 records, <strong>not-HOT update</strong>, average time <strong>~22ms</strong>:</p><pre>Update on spaces  (cost=0.43..844.24 rows=100 width=656) (actual time=20.232..20.254 rows=0 loops=1)</pre><pre>-&gt;  Index Scan using spaces_pkey on spaces  (cost=0.43..844.24 rows=100 width=656) (actual time=0.063..6.511 rows=100 loops=1)</pre><pre>Index Cond: (id = ANY (&#39;{2398499,4590088,2755979,...}&#39;::bigint[]))</pre><pre>Planning Time: 0.205 ms</pre><pre><strong>Execution Time: 20.324 ms</strong></pre><p>Base configuration + <strong>1 <em>dlg_user_ids_index</em> index, not-HOT update</strong>, 100 records, average time ~<strong>64ms</strong></p><pre>Update on spaces  (cost=0.43..844.24 rows=100 width=656) (actual time=73.879..73.897 rows=0 loops=1)</pre><pre>-&gt;  Index Scan using spaces_pkey on spaces  (cost=0.43..844.24 rows=100 width=656) (actual time=1.377..41.769 rows=100 loops=1)</pre><pre>Index Cond: (id = ANY (&#39;{5578295,5815602,....}&#39;::bigint[]))</pre><pre>Planning Time: 0.281 ms</pre><pre><strong>Execution Time: 73.965 ms</strong></pre><p>Base configuration +<strong> 1 <em>chats_uuid_index</em> index, not-HOT update</strong>, 100 records, average time ~<strong>45ms</strong></p><pre>Update on spaces  (cost=0.43..844.24 rows=100 width=656) (actual time=47.357..47.446 rows=0 loops=1)</pre><pre>-&gt;  Index Scan using spaces_pkey on spaces  (cost=0.43..844.24 rows=100 width=656) (actual time=0.061..24.770 rows=100 loops=1)</pre><pre>Index Cond: (id = ANY (&#39;{2594083,4525270,...}&#39;::bigint[]))</pre><pre>Planning Time: 0.242 ms</pre><pre><strong>Execution Time: 47.517 ms</strong></pre><blockquote><strong>Rem. </strong>The average size of indexed data uuid vs text in a given set of data is 16 / 24.77 ~ 2:3</blockquote><h4>Trade-offs and summary</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0aac4d34bd67aae62fbad2d6734e174e/href">https://medium.com/media/0aac4d34bd67aae62fbad2d6734e174e/href</a></iframe><p>INSERT operation with a trigger and a helper-table is <strong>~ 2–2.5 times</strong> slower than normal index solution. (+<em>2ms </em><strong><em>VS</em></strong><em> +5ms</em>).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/252bb32f7646492713de48d18dc0b0fc/href">https://medium.com/media/252bb32f7646492713de48d18dc0b0fc/href</a></iframe><p>UPDATE request is far more expensive operation than INSERT. Its 3–12 times slower than INSERT depending on a HOT/non-HOT execution and indexes amount.</p><ul><li>+1 unique text index slowed not-HOT updates ~3 times against non-HOT updates done with a pkey and +1 int64 indexes. ( <em>+22ms VS +64ms</em> )</li><li>+1 uuid based uniq index slowed base configuration ~2 times for non-HOT updates ( <em>+22ms VS +45ms</em> )</li></ul><p>One time deal <strong>+1ms overhead</strong> on a records INSERT <strong>will save 14ms</strong> on <strong>every non-HOT UPDATE</strong>! ( 8.4ms-5.5ms=2.9ms <strong>VS</strong> 64ms-22ms=42ms )</p><h4>Conclusion</h4><p>Delegating uniqueness to a standalone helper table via INSERT trigger might be a reasonable idea for special cases of ‘imutable’ or ‘short term’ uniqueness, but with one strong condition: you should have noticeable amount of non-HOT updates*</p><blockquote>*To get your numbers use cool dba helpers from <a href="https://github.com/NikolayS/postgres_dba">https://github.com/NikolayS/postgres_dba</a>.</blockquote><h3>Appendix</h3><h4>Why delegated uniqueness for optimistic creation is better than ‘mutex’ based solution.</h4><blockquote>To be honest this was the original idea on the matter how to avoid the UNIQUE index for optimistic entity creation.</blockquote><p>Another way to handle optimistic creation is to use some kind of a ‘mutex’, for instance, based on redis.</p><p>In short:</p><ul><li>SETNX with uuid as a key set to -1 with TTL whenever entering entity creation and check what was there before.</li><li>If value exists and equals to -1 — we are in race condition and should wait till uuid key is freed by timeout or creation process success.</li><li>If value exists and equals to pkey — return existing object.</li><li>after successful creation SET uuid with recieved entity pkey.</li></ul><p>You can combine this mutex with DB triggers and callbacks trying to avoid +1 index creation. But while being an improvement to the process happened without it, ‘mutex’ approach still not 100% solid. You need to do +1 round trip to redis, redis can loose your ‘mutexes’, application can fail after record creation happened but before pkey stored in mutex, you need to add code for handling race condition, you still cannot be sure that mutex freed via timeout really failed and so on.</p><p>On the other hand having delegated uniqueness inside Postgres is solid, simple and much faster.</p><h4>Ruby gem</h4><p>Good news for ruby users: I will extract delegated uniqueness feature into the <a href="https://github.com/alekseyl/izolenta">izolenta</a> gem, I already cybersquatted the name :)</p><h4>Additional reading</h4><ul><li><a href="https://medium.com/@samokhvalov/how-partial-indexes-affect-update-performance-in-postgres-d05e0052abc">https://medium.com/@samokhvalov/how-partial-indexes-affect-update-performance-in-postgres-d05e0052abc</a></li><li><a href="https://use-the-index-luke.com/sql/dml/insert#fig_insert">https://use-the-index-luke.com/sql/dml/insert</a></li><li><a href="https://postgres.ai/blog/20211029-how-partial-and-covering-indexes-affect-update-performance-in-postgresql">https://postgres.ai/blog/20211029-how-partial-and-covering-indexes-affect-update-performance-in-postgresql</a></li><li><a href="https://github.com/postgres/postgres/blob/master/src/backend/access/heap/README.HOT">https://github.com/postgres/postgres/blob/master/src/backend/access/heap/README.HOT</a></li><li><a href="https://www.cybertec-postgresql.com/en/hot-updates-in-postgresql-for-better-performance/">https://www.cybertec-postgresql.com/en/hot-updates-in-postgresql-for-better-performance/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0fa103f749c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Find your o-t-o soulmate in an o-t-m crowd]]></title>
            <link>https://leshchuk.medium.com/find-your-o-t-o-soulmate-in-a-o-t-m-crowd-bb783a9de4a3?source=rss-afaaebe85f49------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb783a9de4a3</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[postgres]]></category>
            <dc:creator><![CDATA[AlekseyL]]></dc:creator>
            <pubDate>Tue, 08 Jun 2021 16:48:57 GMT</pubDate>
            <atom:updated>2021-06-08T17:07:01.112Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*tiBKTYHlvdsECuePoxA7EQ.jpeg" /><figcaption>Finding the one in the crowded Matrix</figcaption></figure><p>One funny and yet powerful idea related to one-to-one relations came to my mind recently.</p><p>Imagine a simple one-to-one relation whenever a second object always exists. For instance a user and his default virtual folder, whenever a user is created, the user’s default folder should also be created, and it cannot be deleted.</p><p>First of all a pure o-t-o relation is usually pretty useless, just add what’s needed to the table schema and skip the foreign relation part. But let’s say we have one-to-many or many-to-many foreign relations and somewhere in this otm and mtm crowd there is our ‘soulmate’ for which we could say he is the only one or should I say the only one-to-one :)?</p><p>How could be this one-to-one connection established properly?</p><p>Let’s look closer at the first example with users and folders, and let’s say schema connects one user to many folders. Usually this done via a user_id colum added to the folders table. So how we could establish the ‘soulmateness’ over this schema?</p><p><strong>The simpliest way possible</strong>: add some kind of a ‘soulmate’ flag column, and set it to true for the corresponding folder.</p><p>Here is how every user can obtain his soulmate folder:</p><pre>SELECT * FROM folders WHERE user_id = my_id AND soulmate;</pre><p>The more folders users will have on an average, the longer search would become, more iops would be wasted e.t.c.</p><p>We can definitely sky-rocket it with +1 partial index on the user_id column of the folders table with a ‘soulmate = TRUE’ condition. But even a blazing fast search will still require +1 DB query to get users soulmate folder id whenever needed and also we added +1 index size of a users table to our schema.</p><p><strong>The reverse id way: </strong>add soulmate_folder_id to the users table and fill it with the soulmate folder id right after its creation.</p><p>Now a freshly obtained record of myself will reveal my ‘the only one’ folder id, hence I could put something in it without even querying the full folder record.</p><p>Still whenever system has a random folder record it needs a soulmate flag column on the folder record to get the idea is this a ‘just a folder’ or is it ‘the one’ folder for some user in the system. And we still need to add +1 index to find the corresponding user for the ‘someones special’ folders.</p><p><strong>The unusual way: </strong>let them have same PK id! But hold on, sooner or later the amount of folders in the system will outrun the amount of users in it and this would became impossible!</p><p>Yes, unless we <strong>just shift the sequence id for the folders table</strong> as far as reasonable, for instance if the pkeys are 8-bytes ints we could shift sequence by 10 billions, than adding every human in the wolrd will still not be able to fill it completely.</p><pre>SELECT setval( sequence_name, 10_000_000_000::bigint );</pre><p>So the only thing left is to set our soulmate folder pk id equal to user pk id during its creation, and that’s it.</p><p>If folder pk_id is less than shift, then its a soulmate folder for the user with same id, if the folder pk_id is bigger than shift, then its a usual folder. We don’t need to add any new indexes for any of this tables, cause we already should have the pkey indexes in place for both of them.</p><p>The only problem with this approach — you can only go for it at the very beginning. Aligning an existing schema to this approach looks nearly impossible to me. Well nothing is ideal in the world, unless you at least started it like that.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb783a9de4a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zip’em ALL!]]></title>
            <link>https://leshchuk.medium.com/zipem-all-61076c7da4c?source=rss-afaaebe85f49------2</link>
            <guid isPermaLink="false">https://medium.com/p/61076c7da4c</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[AlekseyL]]></dc:creator>
            <pubDate>Thu, 24 May 2018 10:46:48 GMT</pubDate>
            <atom:updated>2018-05-31T06:47:33.293Z</atom:updated>
            <content:encoded><![CDATA[<h4>Optimizing Redis memory usage for strings, integers, jsons and anything you like</h4><p>Whats inside:</p><ul><li>How much +1 symbol to every redis key costs, and does key names optimization worth it?</li><li>Key/value store abstraction over redis hashes. Getting 10 times less memory for stored integers or getting 5% memory discount for medium previews.</li><li>To GZip or not to gzip — comparision of gzipping VS other types of memory optimizations on a various range of data.</li><li>Introducing me-redis gem — all types of redis memory optimization in one set of tools. Tiny code changes for a max result!</li><li>Memory savings ( starting at 2.5 less up to 12 times less memory ) and performance tradeoffs in numbers.</li></ul><h4>Universal memory optimization ideas</h4><p>Redis is one of the most popular key-value in-memory storage&#39;s, it delivers blazing fast O(1) speed for most of its operations. To keep it that way redis refuse to do any additional manipulation to data, like: value zipping, key shredding, auto zip of small objects and so. I see two major reasons for a such decision: a single-threading nature of a Redis and a data structure unawareness on a Redis side. You can’t change Redis nature to multi threading, but you can optimize the way you store your data.</p><p>Here are three different <strong>relatively</strong> <strong>universal</strong> ideas on how to become memory efficient:</p><ol><li>Shorten your keys</li><li><a href="https://redis.io/topics/memory-optimization">Abstract plain key/value store over hash</a> for small objects</li><li>Compress values on application side</li></ol><p>They all have their limitations, and must be used properly. I’ve tried them all, different kinds of their combinations and summarize them to <a href="https://github.com/alekseyl/me-redis">me-redis gem</a> as a ready to go set of tools.</p><h4>Zipping keys</h4><p>Lets start with a key length investigation. Usual point of view is how a key length affect performance: <a href="https://stackoverflow.com/questions/6320739/does-name-length-impact-performance-in-redis">Does name length impact performance in Redis?</a>, <a href="http://adamnengland.com/2012/11/15/redis-performance-does-key-length-matter/">Redis Performance — Does key length matter?</a> and so. But how much is one additional symbol to all keys will impact a memory used?</p><p>Simple assumption for a size of a memory allocated just for storing keys would be a key.length * Keys.count, so +1 symbol to each key may bring +Keys.count bytes to memory used.</p><p>After all it’s quite accurate!</p><p>Only one thing left to mention: a memory growth may not be spotted on each +1 symbol. It’s more like a long stair, where you can do couple of steps on a single stair, but after all there will be another stair and the trend will go linear.</p><p>In numbers: an integer value of 1 stored in 10K key/value pairs, consumes memory around 0.6Mb for 3 symbols per key, 0.9Mb for 20 symbols per key and 2.2Mb for 128 symbols per key. Inspecting memory consumption from 3 symbols to 128 will reveal the trend — <strong>1 byte per symbol</strong>. See code section at the bottom for additional details and key zipping examples.</p><p><strong>Resume for key zipping:</strong> if a value size <strong>is comparable</strong> to a key size, than zipping keys may bring noticeable results. And vice versa: if your value is 1K size, than optimizing 10 bytes on each key will never be more than a 1% memory win.</p><h4>Plain key-value store abstraction over hash</h4><p><a href="https://redis.io/topics/memory-optimization">In official memory optimization topic</a> there is a paragraph: “Using hashes to abstract a very memory efficient plain key-value store on top of Redis”. You can read it in full from a given link, here is the essence:</p><blockquote>Let’s assume the objects we want to cache are numbered, like:</blockquote><blockquote>object:102393</blockquote><blockquote>object:1234</blockquote><blockquote>object:5</blockquote><blockquote>This is what we can do. Every time there is to perform a SET operation to set a new value, we actually split the key into two parts, one used as a key, and used as field name for the hash. For instance the object named “object:1234” is actually split into:</blockquote><blockquote>a Key named object:12</blockquote><blockquote>a Field named 34</blockquote><blockquote>So we use all the characters but the latest two for the key, and the final two characters for the hash field name. To set our key we use the following command:</blockquote><blockquote>HSET object:12 34 somevalue</blockquote><blockquote>As you can see every hash will end containing 100 fields, that is an optimal compromise between CPU and memory saved.</blockquote><h4>A hash abstractions pitfalls</h4><p>Had to mention that if integer tail of keys is rarely distributed, than such sharding leads to hashes with a very few keys, making this approach is wore than useless.</p><p>Example:</p><pre># code similar to redis guide <br># without hash-max-ziplist-entries awareness</pre><pre>def custom_incr(key)<br>  split = <em>key</em>.scan(/(.*)(\d{2,2})$/).flatten<br>  split.length == 0 ? <em>key</em>.scan(/(.*)(\d{1,1})$/).flatten : split<br>  hincrby(*split, 1)<br>end</pre><pre>redis.pipelined { <br>   10000.times {|i| redis.custom_incr(&quot;user:#{i}&quot;) } <br>}</pre><p>Allocates only 70kb for 10K records! This because of i is consequent. Lets make HOLES!</p><pre>redis.pipelined { <br>   10000.times {|i| redis.custom_incr(&quot;user:#{rand(1000000)}&quot;) } <br>}</pre><p>Holey-molly, it’s a 685Kb, practically same size as incr would do. Of course it would do, since 1000000 / 10000 equals 100 — the exact shard size. This means roughly one element per hash, “quite an optimization”!</p><h4>hash-max-ziplist-value and hash-max-ziplist-entries</h4><p>A redis topics <strong>code example </strong>(not the topic itself)<strong> </strong>actually ignores them. But you need either to set hash-max-ziplist-entries to 100 or to use the real hash-max-ziplist-entriesvalue as a sharding size to be productive.</p><p>For example if a default value for hash-max-ziplist-entries is 64, than using 100 as a sharding size is a bad idea, because:</p><blockquote>If a specially encoded value will overflow the configured max size, Redis will automatically convert it into normal encoding.</blockquote><p>Same with hash-max-ziplist-value you need to be aware of your hash-max-ziplist-value size, otherwise you’ll break the optimization and go back to usual key/value pairs.</p><p>If hash-max-ziplist-entries value is greater than shard size this is not a disaster just resource waster. For a given case of “holey-molly” real number of hash-max-ziplist-entries was actually 512, and 412 slots were “wasted”. Using sharding size of 512 would give us a 5 keys per hash roughly, and 260Kb of allocated memory, compared to 700kb for direct key/values.</p><p><strong>Hash abstractions resume:</strong></p><p>This kind of optimization must be:</p><ul><li>aware of a size of a stored data,</li><li>aware of a keys structure ( you need to shard properly so you must understand the nature of a keys structure ),</li><li>aware of hash-max-ziplist-value and hash-max-ziplist-entries values, or directly set them, to keep this memory optimization working.</li></ul><p>A memory discount is limited: you <strong>can’t get </strong><a href="https://github.com/sripathikrishnan/redis-rdb-tools/wiki/Redis-Memory-Optimization#avoid-small-strings"><strong>more than 90 bytes</strong> from each key/value pair</a>! It may be a huge win for storing integers, and only a 10% for 1K strings, for example short previews on main page of medium.com is 5K size, so it’s 5% less memory then.</p><h4>Values compression</h4><p>This is not the Redis specific topic, so I’ll get straight to the resume.</p><p>The bad parts:</p><ul><li>its never performance free, at application level it will slowdown your code.</li><li>general string compression algorithms may not compress well all kinds of strings, may not even compress :). For example, short strings compressed with general purpose compression algorithm usually getting even bigger.</li></ul><p>The good part: it may be the only way to optimize memory consumption for large values.</p><h4>Zip’em ALL, introducing me-redis gem</h4><p>Disclaimer: me — states for Memory Efficient.</p><p>Features:</p><ul><li>seamless integration with code already in use, apart from me_* methods it’s all in MeRedis configuration, not your current code.</li><li>hash key/value optimization with seamless code changes, you can replace set(‘object:id’, value) with me_set( ‘object:id’, value) and free 90 byte for each [‘object:id’, value] pair.</li><li>zips user-friendly key crumbs, i.e. converts for example user:id to u:id</li><li>zip integer parts of a keys with base62 encoding. Since all keys in redis are always strings, than we don’t care for integers parts base, and by using base62 encoding we can ~1.8 times shorten integer crumbs of keys</li><li>respects pipelined and multi, properly works with futures.</li><li>different compressors for different keys namespaces. You can compress objects, short strings, large strings, primitives with a best suitable way for each other.</li><li>hot migration module with fallbacks.</li></ul><h4>Memory discount in numbers</h4><p>Memory consumption comparison are done for a 100K pairs for a keys from <a href="https://stackoverflow.com/questions/6320739/does-name-length-impact-performance-in-redis">stackoverflow question</a>: set-allBooksBelongToUser:id, hash-max-ziplist-value is set big enough to contain any piece of a tested data.</p><p>Values sets are: integers, plain English strings variable length, html pieces variable length, ActiveRecord objects json serializations of two different models. The values inside cells are Mb of memory used, cleared from clear Redis base memory use (~500Kb).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/300fcca5993bf98f5e875d08d0dfab2f/href">https://medium.com/media/300fcca5993bf98f5e875d08d0dfab2f/href</a></iframe><p>It’s all in the tables but I’ll make some short over all resume:</p><ul><li>best result is <strong>12 times less memory</strong> for compacting integers to hash abstraction with key zipping.</li><li>other datatypes: short plain English strings smaz compressor show best result — <strong>3 times less memory </strong>(it’s generally useless compressor but still for an example purpose), <strong>2.5–3 times less memory</strong> for large strings or html pieces with gz compression, <strong>3 times less memory</strong> for object serialization with a custom compressor and full set of optimization.</li><li>idea of optimized compressors for namespaces may work well since there isn’t any universal compressor for all datatypes. You can tune performance and compression independently.</li><li>using a hash optimization works better with small types, and not so well with large, because it brings nearly fixed result by freeing ~100-bytes per pair.</li></ul><h4>Perfomance tradeoffs</h4><p><strong>At redis level</strong> we speaking only about comparison between hash abstraction performance against classic methods. So we are comparing get/set/incrby to hget/hset/hincrby and also advanced commands like getset, mget, mset to transaction wrapped multiple calls of hget/hset.</p><ul><li>get/hget VS incrby/hincrby — same-ish,</li><li>hset VS set — hset is slightly faster.</li><li>mget/mset VS multi + mget/hset — mget/mset are faster, dependent on how much values we try to set at once.</li></ul><p>You can recheck all with <a href="https://redis.io/topics/benchmarks">redis-benchmark tool</a> by yourself.</p><p><strong>At ruby level</strong>, of course doing nothing is instant fast against pipelining multiple calls, compressing values, decomposing and recomposing keys.</p><p>I will measure only clear me_method performance for single namespace, leaving out compression impact. <strong>Single calls</strong> goes from same-ish for me_set/me_get/me_incr to 1.7 times slowdown for me_mset/me_mget, for <strong>10 pipelined operations</strong> in a row me_get/me_set/me_incr methods show 30–50% slowdown, me_mset/me_mget are 2–3 times slower than mset/mget , for <strong>100 pipelined operations </strong>in a row me_get/me_set/me_incr show similar results — 30–50% slowdown, me_mset/me_mget’s slowdown shows logarofmic growth — to 3.5–4 times less performant. All details at the bottom section.</p><p>Compression tradeoff — depends on the algorithm and compression level, it’s up to you to decide what is the best for you.</p><h4>Links:</h4><ol><li>Redis official guide in <a href="https://redis.io/topics/memory-optimization">memory optimization</a>.</li><li><a href="http://labs.octivi.com/how-we-cut-down-memory-usage-by-82/">How we cut down memory usage by 82%</a></li><li><a href="https://stackoverflow.com/questions/6320739/does-name-length-impact-performance-in-redis">Does name length impact performance in Redis?</a></li><li><a href="http://adamnengland.com/2012/11/15/redis-performance-does-key-length-matter/">Redis Performance — Does key length matter</a></li><li><a href="https://github.com/sripathikrishnan/redis-rdb-tools/wiki/Redis-Memory-Optimization">Redis memory optimization practical advices</a></li><li><a href="https://sorentwo.com/2015/08/10/efficient-redis-caching-through-hashing.html">Caching through hashing</a></li><li><a href="https://redis.io/topics/benchmarks">Redis benchmark tool</a>, <a href="https://stackoverflow.com/a/33293802/4495899">benchmarking hset/hget</a></li><li><a href="https://stackoverflow.com/questions/16375188/redis-strings-vs-redis-hashes-to-represent-json-efficiency/50567485#50567485">Strings VS Hashes stackoverflow question</a></li></ol><h3>Code samples, benchmarking, CLI outputs e.t.c.</h3><h4>Memory consumption VS key size:</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a854f8aa3e6046b1097ceb6872547ee6/href">https://medium.com/media/a854f8aa3e6046b1097ceb6872547ee6/href</a></iframe><h4>Key zipping example:</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c84cbf05ce924993698bec2ec2362077/href">https://medium.com/media/c84cbf05ce924993698bec2ec2362077/href</a></iframe><h4>Me methods raw performance to original</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c44454d06f10f7ae695ef8d9d942ef9a/href">https://medium.com/media/c44454d06f10f7ae695ef8d9d942ef9a/href</a></iframe><h4>Custom compressors example</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28e24068cc7976ca5ccda5fe82550b6b/href">https://medium.com/media/28e24068cc7976ca5ccda5fe82550b6b/href</a></iframe><h4>MeRedis config example</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/985c0d15c9f6cef836c6a9d63cd1155e/href">https://medium.com/media/985c0d15c9f6cef836c6a9d63cd1155e/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61076c7da4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple sample в ruby и Postgres’е. (рус)]]></title>
            <link>https://leshchuk.medium.com/simple-sample-%D0%B2-ruby-%D0%B8-postgres%D0%B5-%D1%80%D1%83%D1%81-6ded79351132?source=rss-afaaebe85f49------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ded79351132</guid>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[AlekseyL]]></dc:creator>
            <pubDate>Fri, 09 Mar 2018 11:32:23 GMT</pubDate>
            <atom:updated>2018-03-13T14:01:07.912Z</atom:updated>
            <content:encoded><![CDATA[<p>English version: <a href="https://medium.com/@leshchuk/simple-sample-for-postgres-and-ruby-ca44aa689c2c">Simple sample for Postgres and ruby</a>.</p><p>Что интересного в статье:</p><ol><li>Пример быстрого псевдослучайного семплинга массивов в постгресе и руби.</li><li>Сравнение различных реализаций сэмплирования массивов в постгресе и руби, с предложенным: <strong>Для постгреса</strong> на массивах в 1000 элементов в<strong> 6.5 раз быстрее</strong> комбинации order by random() ( <strong>в 15 раз </strong>на 10К элементах) и в 4 раз быстрее процентной выборки random() &lt; 0.xx ( в 10 раз на 10К элементах ). <strong>Для руби </strong>на массивах от 2000 элементов и от 11 элементов в выборке — нарастающая разница в пользу предложенного варианта.</li><li>Основной недостаток сэмплирования через TABLESAMPLE SYSTEM и SYSTEM_ROWS и как его преодолеть.</li><li>Пример STABLE функции для построения псевдослучайной последовательности и почему это важно.</li></ol><h4>Выборка элементов</h4><p>Задачи получения выборки от множества, встречаются сплошь и рядом в решении как прикладных так и системных задач.</p><p>Сэмплирование может быть последовательным — взять из множества M элементов подряд, и рандомизированным — получить из множества M случайных элементов. Пример для последовательного семплирования: разбивка длинных списков на страницы, пример рандомизированной выборки: сбор статистики по таблице для планировщика БД, для того чтобы планировать выполнение запроса нужно периодически проводить рандомизированное сэмплирование и по нему собирать статистику, на основе которой будет строиться план запроса.</p><p>Если получаемая выборка выводится пользователю без дополнительной обработки, то ее размеры не должны отклоняться от M, а сама выборка не должна содержать дубликатов.</p><p>Зафиксируем N для обозначения количества элементов множества, а M для количества элементов в выборке.</p><h4>Выборка из M частей</h4><p>Для создания псевдослучайной выборки из M элементов предлагается вариант, когда множество из N элементов разбивается на M частей и в каждой из этих M частей выбирается один случайный элемент.</p><p><strong>Преимущества</strong>:</p><ul><li>выборка проходит в один проход, не нужны вложенные циклы для проверки на случай повторных выпаданий, так как M частей гарантировано не пересекаются.</li><li>количество вызовов функции random или ее аналогов меньше количества элементов исходного множества, что очень существенно, если выборка M сильно меньше размеров множества N.</li><li>количество элементов в выборке не может плавать и всегда соответствует указанному.</li></ul><p><strong>Недостатки</strong>:</p><ul><li>выборка является псевдослучайной и не дает всех возможных комбинаций M элементов из N. Количество комбинаций в случае полностью случайного выбора элементов будет соответствовать биноминальному коэффициенту N!/M!(N-M)!, предложенная псевдослучайная выборка даст нам в общем случае (N/M) в степени M вариантов. Например для случая когда M = 2, полное количество комбинаций = N*(N-1)/2 , для псевдослучайной выборки — N*N/4, т.е. чуть больше половины всех возможных вариантов.</li><li>нужно знать исходные размеры множества, что не является обязательным в ряде реализации случайных выборок. Как-то: <a href="http://web.archive.org/web/20080214235745/http://www.powerpostgresql.com/Random_Aggregate">random_agg</a> для одного элемента, процентные выборки типа TABLESAMPLE BERNOULLI или ее аналогов ( когда мы для каждого элемента кидаем монетку для определения его вхождения/невхождения в выборку ).</li><li>M должно быть как миниммум не меньше N/2, а еще лучше в несколько раз меньше N, чем больше разница тем лучше.</li></ul><h3>Ruby</h3><p>Давайте сравним текущую реализацию метода sample массива в руби и предложенный алгоритм.</p><p>Если глянуть в исходники можно вынести следующее: функция sample разбита на несколько частных случаев:M = 1, 2, 3, M ≤10, M=N и последний самый общий случай M &gt; 10. Даже без практической проверки можно предположить, что тягаться с частными оптимизированными случаями, реализованными на языке С бесполезно, поэтому давайте посмотрим на случай “все остальное” т.е. случай когда M &gt; 10, но в несколько раз меньше N.</p><p>Анализируя исходный код для этого случая ( см приложение, выделено жирным ), можно увидеть, что, несмотря на всю элегантность решения, происходит полное копирование исходного массива, а затем его обрезка до M нужных для выборки элементов. Ожидаемо, что с определенных размеров массива это будет тормозить исполнение функции и перерасходовать память.</p><p>Прикинем на практике чем как это будет соотноситься с такой реализацией:</p><pre><strong>class Array<br>  def </strong>pseudo_random_sample(<em>count</em>)<br>    result = Array.new(<em>count</em>)<br>    piece_size = length / <em>count<br>    </em>reminder = length - piece_size * <em>count<br>    count</em>.times do |<em>i</em>| <br>      result[<em>i</em>] = ( <em>i &lt; count </em>- 1 ?<br>                  self[rand(piece_size) + <em>i</em>*piece_size] :<br>                  self[rand(piece_size + reminder) + <em>i</em>*piece_size] )<br>    end<br>    result<br><strong>  end<br>end</strong></pre><p>По результатам сравнения для 11 элементов рубежом на моей машине выступил размер массива в 2000 integer’ов (что составляет чуть больше 16кб памяти и соответствует 5 страницам памяти), примерно с этого размера нативная реализация сэмпла начинает проигрывать.</p><p>Пример сравнения производительности на выборке из 11 элементов на массиве из 100К элементов ( M = 11, N = 100K ).</p><pre>Warming up --------------------------------------<br>            .......................<br>Calculating -------------------------------------<br>             classic    3.666k (± 4.8%) i/s   - 18.564k in  5.07s<br>           m-partial    192.859k (± 5.9%) i/s - 967.470k in 5.03s<br>  m-partial+shuffle!    177.411k (± 5.2%) i/s - 893.048k in 5.04s</pre><pre>Comparison:<br>           m-partial:   192859.0 i/s<br>  m-partial+shuffle!:   177410.8 i/s - same-ish<br>             classic:     3666.2 i/s - <strong>52.60x  slower</strong></pre><p>Как видно разница составила скромные 52 раза, конечно с ростом числа M это соотношение будет уменьшаться и для N = 100K сравняется в районе M ~ 700.</p><p>Если использовать выборки до 10 элементов включительно или массив меньше 2000 элементов, то разница между оригинальным методом на C и данной реализацией на руби будет ожидаемо не в пользу метода на руби, проигрыш составит где-то <strong>2–3.5 раза</strong> в зависимости от размеров массива и выборки.</p><p>Если не устраивает, что выбранные элементы сохраняют свою очередность, можно сделать такой финт:</p><pre>arr.random_sample(sample_size).shuffle!</pre><p>Это дополнительно перемешает полученные элементы, всего лишь за 29.99 :)! На самом деле примерно за ~ 5-10% потерю в производительности в зависимости от размеров выборки M, что и отражено в таблице в строке m-partial+shuffle!.</p><h3>PostgreSQL sample для массивов.</h3><h4>Последовательная выборка</h4><p>Напомню, что для получения последовательного семпла массива можно использовать конструкцию: [a:b], где a и b индексы в массиве, удовлетворяющие соотношению a ≤ b и лежащие в пределах индексов массива, по умолчанию нумерация начинается с 1.</p><p>Пример получения двух первых элементов массива user_ids:</p><pre>SELECT user_ids[1:2] FROM docs LIMIT 1;</pre><pre>   user_ids    <br>---------------<br> {70049,51869}</pre><h4>Случайная/псевдослучайная выборка</h4><p>Встроенной функции на извлечение случайного сэмпла у массива нет. Дальше у нас есть два варианта: первый это вызвать unnest на массив и, получив набор записей, использовать подходы, которые используются для обычных таблиц или написать свой аналог такой функций. Давайте реализуем оба подхода и сравним производительность.</p><h4>Построение случайной выборки для таблиц</h4><p>Вот достаточно полный список вариантов сэмплирования таблиц, который можно составить поискав решение в интернете:</p><ol><li>TABLESAMPLE ( и его расширение tsm_system_rows)</li><li>ORDER BY random() LIMIT M</li><li>WHERE random() &lt; 0.xx ( аналогично TABLESAMPLE BERNOULLI)</li><li>+1 Indexed random value column</li><li>Вариации на тему: WHERE id IN ( SELECT random() * id_max FROM generate_series(1, M) )</li><li>Адаптация <a href="http://web.archive.org/web/20080214235745/http://www.powerpostgresql.com/Random_Aggregate">random_agg</a> для выборки не одного, а M элементов ( это придется писать самостоятельно и обосновывать ).</li></ol><h4>Что для массивов не сработает:</h4><p>TABLESAMPLE — невозможно использовать для массивов.</p><p>+1 Indexed random value column — тоже для работы с массивом не подходит.</p><h4>Что сработает с массивами</h4><pre><strong>ORDER BY random() LIMIT M</strong> </pre><p>Дает гарантированных M элементов, но производит при этом сортировку! Как правило <strong>такие решения получаются самыми медленными</strong>.</p><pre><strong>WHERE random() &lt; M/N</strong> </pre><p><strong>Не дает гарантированного количества строк</strong>, но исключает сортировку. Если необходимо гарантированное колличество строк, метод потребует дополнительного усложнения алгоритма, но он идеально подходит для минимальной оценки производительности алгоритмов, вызывающих функцию random() N раз. Таких как, например, random_agg, который помимо N вызовов random() будет содержать дополнительную логику, что в среднем увеличит время его исполнения.</p><pre><strong>Адаптация </strong><a href="http://web.archive.org/web/20080214235745/http://www.powerpostgresql.com/Random_Aggregate"><strong>random_agg</strong></a><strong> для варианта M &gt; 1</strong></pre><p>Можно заморочиться и переписать <a href="http://web.archive.org/web/20080214235745/http://www.powerpostgresql.com/Random_Aggregate">этот алгоритм </a>для варианта с выборкой не одного, а M элементов, но для оценки производительности, как уже было сказано, достаточно ограничиться вышеописанным вариантом (= where random() &lt; M/N), который будет гарантировано быстрее и даст оценку снизу для подобного решения.</p><pre><strong>SELECT arr[random() * arr_length] FROM generate_series(1, M)</strong>. </pre><p>В частности его аналог предлагают в статье <a href="https://www.periscopedata.com/blog/how-to-sample-rows-in-sql-273x-faster">How To Sample Rows in SQL 273X Faster</a>:</p><pre>select * from users<br>where id in (<br>  select round(random() * 21e6)::integer as id<br>  from generate_series(1, 110) -- Preserve duplicates<br>)<br>limit 100</pre><p>У такого способа помимо проблемы повторов, которую пытаются вылечить, увеличив выборку на 10%, добавляется другая проблема: в случае неравномерного распределения id, могут быть не только повторы, но и недобор элементов, если было много удалений из таблицы.</p><p>Данный способ неплохо подойдет, если полученная выборка будет преобразовываться и анализироваться, но для непосредственной выдачи пользователю не годится, потому что будет скакать размер выборки, если же алгоритм доводить, то требуемое усложнение отрицательно скажется на его производительности и элегантности.</p><h4>Сравнение производительности</h4><p>Код функций:</p><pre>-- order by random<br>CREATE OR REPLACE FUNCTION random_sample_obr( bigint[], int ) RETURNS TABLE (id bigint) AS $$<br>  SELECT * FROM unnest($1) ORDER BY random() LIMIT $2;<br>$$ LANGUAGE SQL;</pre><pre>-- less than random<br>CREATE OR REPLACE FUNCTION random_sample_lr( bigint[], int ) RETURNS TABLE (id bigint) AS $$<br>DECLARE<br>  -- probability is same for all set, so it must be evaluated once<br>  probability float := $2::float / cardinality($1);<br>BEGIN<br>  RETURN QUERY SELECT * FROM unnest($1) WHERE random() &lt; probability;<br>END<br>$$ LANGUAGE plpgsql;</pre><pre>--generate series analogue <br>CREATE OR REPLACE FUNCTION random_sample_gs( arr bigint[], sample_size int ) RETURNS TABLE (id bigint) AS $$<br>DECLARE<br>  arr_length int := cardinality(arr);<br>  result bigint[];<br>BEGIN<br>  FOR i IN 1..sample_size LOOP<br>    result[i] = arr[floor(random()*arr_length)];<br>  END LOOP;<br>END<br>$$ LANGUAGE plpgsql;</pre><pre>--M-partial sample<br>CREATE OR REPLACE FUNCTION random_sample_mp( arr bigint[], sample_size int ) RETURNS bigint[] AS $$<br>DECLARE<br>  result bigint[];<br>  piece_size int := cardinality(arr) / sample_size;<br>  reminder int := cardinality(arr) - piece_size * sample_size;<br>BEGIN <br>  FOR i IN 1..sample_size LOOP<br>    IF i = sample_size THEN<br>      result[i] := arr[floor((piece_size + reminder)*random() + 1) +         <br>                   (i-1)*piece_size];<br>    ELSE<br>      result[i] := arr[floor(piece_size*random() + 1) + <br>                  (i-1)*piece_size];<br>    END IF;<br> <br>  END LOOP; <br>  RETURN result;<br>END<br>$$ LANGUAGE plpgsql;</pre><p>Статистика собрана по результатам 100 случайных запросов типа:</p><pre>SELECT random_sample_XXX( user_ids, 5 ) as uid <br>  FROM &quot;cards&quot; <br>-- 10 random ids from cards, generated outside time measurement<br>  WHERE &quot;cards&quot;.&quot;id&quot; IN (...)</pre><p>Изначально сравнение проводилось для нескольких размеров массивов (=N), для нескольких элементов из массива ( =M ), для случайно формируемых наборов из K элементов. Ожидаемо, что наибольшая зависимость оказалась от размеров массива: с ростом числа элементов в массивах, все остальные зависимости ушли на второй план, поэтому в результирующей таблице оставлена только зависимость от размеров массива.</p><p>Значения данных в колонке: время на получения сэмпла и во сколько раз оно хуже/лучше M-partial выборки для данной размерности.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98f3eeeac41f55ced3616e72068aab52/href">https://medium.com/media/98f3eeeac41f55ced3616e72068aab52/href</a></iframe><p>Как видно только упрощенный до некорректности вариант с рандомным извлечением M элементов ( эквивалент generate_series ), опережает на малых размерах M-partial вариант. При этом с ростом массива разница в производительности между ними стремится к нулю, а вероятность получения совпадения одной и больше пары в выборке при использовании эквивалента generate_series, стремится к 1.</p><h4>Sample from TABLESAMPLE</h4><p>TABLESAMPLE SYSTEM и TABLESAMPLE SYSTEM_ROWS рекордсмены по производительности среди всех спобов сэмплирования на таблицах. Но оба эти варианта страдают от одного серьезного недостатка: выборка рандомизирована постранично, а не построково, поэтому при выдаче выборки с малым M легко получить последовательные наборы.</p><p>Например для таблицы с 1.1M записями, для такого запроса:</p><pre>SELECT array_agg(id) FROM docs TABLESAMPLE SYSTEM_ROWS(5);</pre><p>Легко получить такие результаты:</p><pre>{2083068,2083069,2083070,2083071,2083072}</pre><pre>OR</pre><pre>{1168539,1168541,1168542,1168547,1168551}</pre><p>И это не совсем то, что хотелось получить от случайной выборки.</p><p>Но это легко исправить используя такой трюк:</p><pre>SELECT random_sample(array_agg(id), 10) <br>FROM cards TABLESAMPLE SYSTEM(1);</pre><p>Супербыстрый, никакой пагинации, никаких дубликатов и плавающего размера выборки!</p><h4>STABLE random_sample</h4><p>В Postgres есть три способа декларирования функции: <a href="https://www.postgresql.org/docs/10/static/xfunc-volatility.html">STABLE, IMMUTABLE и VOLATILE</a>. По умолчанию функция попадает в категорию VOLATILE. Это означает что ее вызовы не могут быть оптимизированы планировщиком, что может приводить к весьма не ожиданным результатам.</p><p>Давайте рассмотрим такой запрос:</p><pre>SELECT * FROM docs<br>JOIN users ON users.id = ANY( random_sample(user_ids, M) ) <br>WHERE docs.id = ID;</pre><p>Желаемое и ожидаемое поведение однократный вызов функции random_sample, передача ее результатов для поиска все пользователей с такими ID. Но по умолчанию Postgres будет интерпретировать этот запрос как такой:</p><pre>SELECT * FROM docs<br>JOIN users ON random()<br>WHERE docs.id = ID;</pre><p>И здесь очевидно мы вызовем random_sample <strong>для всех строк из таблицы users</strong>, все потому что random() объявлена как VOLATILE, что является значением по умолчанию в Postgres.</p><p>Можно декларировать VOLATILE функцию как STABLE, и планировщик скорее всего соптимизирует ее вызовы, например приведенный выше запрос сработает так как мы ожидаем: вызов ф-ии random_sample будет однократным. <strong>Скорее всего, не значит обязательно! </strong>Пытаться обмануть планировщик замаскировав VOLATILE функцию простым декларированием достаточно опасно.</p><p>Поэтому было бы удобно построить random() как по-настоящему STABLE функцию. В силу того что нам не нужна здесь криптографическая стойкость, мы можем использовать простой линейный конгруэнтный метод, например в такой реализации:</p><pre>CREATE FUNCTION random_stable( prev bigint ) RETURNS int AS $$<br>BEGIN<br>   RETURN (prev * 1103515245 + 12345) / 65536 % 32768; <br>END;<br>$$ LANGUAGE plpgsql IMMUTABLE;</pre><p>После этого все вызовы random() придется заменить на:</p><pre>random_value := random_stable(random_value);</pre><p>Для того чтобы получить первый элемент последовательности воспользуемся другой STABLE функцией: current_timestam. Вот так:</p><pre>random_value := random_stable( extract( microseconds FROM  current_timestamp) );</pre><p>Теперь у нас есть случайная последовательность по-натсоящему стабильная в пределах транзакции и даже, если планировщик примет неожиданное решение конечный результат будет по-прежнему корректен.</p><h4>Оптимизация на стыке ORM и БД</h4><p>Есть еще несколько интересных решений для оптимизации на стыке ORM и БД: разворачивание цикла в один запрос для небольших М, прегенерация случайной последовательности на стороне ORM, а также использование исходного алгоритма на руби.</p><p>Начнем с последнего, как я уже упоминал: основная проблема сэмплинга, портящая элегантное решение на руби, это полное копирование массива для случая M &gt; 10. Но внутри функции мы уже оперируем именно копией массива, и мы уже потратили время на его копирование и нам его не сэкономить, поэтому мы можем с копией делать что хотим, в том числе преобразовать согласно классическому алгоритму:</p><pre>CREATE OR REPLACE FUNCTION random_sample_ruby_way( arr bigint[], sample_size int ) RETURNS bigint[] AS $$<br>DECLARE<br>  current_rand bigint;<br>  j int := 0;<br>  arr_size int := cardinality(arr);<br>  swapper bigint := 0;<br>BEGIN<br>  current_rand := extract( milliseconds FROM  current_timestamp)::int;<br> <br>  FOR i IN 1..sample_size LOOP<br>    current_rand := random_stable(current_rand);<br>    j := current_rand % ( arr_size - i ) + i;  <br>    swapper := arr[j];<br>    arr[j] := arr[i];<br>    arr[i] := swapper;<br>  END LOOP; <br>  RETURN arr[:sample_size];<br>END<br>$$ LANGUAGE plpgsql STABLE;</pre><p>В итоге у нас есть скорость M-partial решения без его проблем!</p><p>Теперь шагнем еще далье и избавимся от вызовов random() внутри функции, просто передав внутрь сгенерированную на стороне ORM псевдослучайную последовательность. Функция выше трансформируется, например, таким образом:</p><pre>CREATE OR REPLACE FUNCTION random_sample_pregenerated_sequence( arr bigint[], random_arr int[] ) RETURNS bigint[] AS $$<br>DECLARE<br>  j int := 0;<br>  arr_size int := cardinality(arr);<br>  sample_size int := cardinality(random_arr);<br>  swapper bigint := 0;<br>BEGIN<br> <br>  FOR i IN 1..sample_size LOOP<br>    j := random_arr[i] % ( arr_size - i ) + i;  <br>    swapper := arr[j];<br>    arr[j] := arr[i];<br>    arr[i] := swapper;<br>  END LOOP; <br>  RETURN arr[:sample_size];<br>END<br>$$ LANGUAGE plpgsql STABLE;</pre><h4>Разворачивание M-Partial алгоритма в строку</h4><p>Если массив маленький, то строка таблицы не будет “поджариваться” т.е. не становится TOASTed. В доках Postgres’а описаны условия, для которых запись начинает, поджариваться:</p><blockquote>The TOAST management code is triggered only when a row value to be stored in a table is wider than <em>TOAST_TUPLE_THRESHOLD</em> bytes (normally 2 kB).</blockquote><p>Для массива данных bigint это ~ 250 элементов, с учетом того, что запись редко состоит только из одного массива и дополнительно содержит еще не только пользовательские данные, но и системные я бы обозначил эффективный рубеж сверхэффективно работы с массивами: 200 элементов.</p><p>Для такого случая супер быстро будет работать разворачивание цикла в строку запроса на стороне ORM:</p><pre>SELECT *, ARRAY[<br>   user_ids[30776 % (cardinality(user_ids)/M)],<br>   user_ids[12021 % (cardinality(user_ids)/M) +   <br>           cardinality(user_ids) * i / M] <br>   ...<br>   user_ids[5410 % (cardinality(user_ids)/M + <br>                     cardinality(user_ids) % M ) +   <br>           cardinality(user_ids) * (M-1)/ M]<br>] as sample <br>FROM docs;</pre><p>Конечно это будут уже достаточно уродливые запросы, но они вполне автоматизируемы.</p><p>Итоговая табличка различных реализаций с переводом главных конкурентов на STABLE реализации* и нормализованная по самому быстрому из них для каждого случая выглядит следующим образом**:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4fb12b778799a7825e67d64b1ff1d5ae/href">https://medium.com/media/4fb12b778799a7825e67d64b1ff1d5ae/href</a></iframe><p>*ORDER BY random() и random() &lt; M/N используют базовую реализацию.</p><p>**Вариант generate_series не совсем корректен и используется как маркер производительности.</p><p>Как видно для размеров меньше TOASTed разворачивание в строку M-partial алгоритма показывает супер быстрый результат даже на малых размерах массива. В остальном классическое корректное исполнение взятое из руби выглядит отличным компромисом между производительностью и корректностью. Для получения еще +50% ускорения можно использовать M-partial выборку, если полнота не обязательна.</p><h4>Список литературы</h4><ol><li><a href="https://stackoverflow.com/questions/24851986/return-random-no-repeating-rows-from-a-table-postgresql">Return random, no-repeating rows from a table — PostgreSQL</a></li><li><a href="https://www.periscopedata.com/blog/how-to-sample-rows-in-sql-273x-faster">How To Sample Rows in SQL 273X Faster</a>( не совсем корректный метод выборки случайных записей из таблицы + содержит еще одну маленькую ошибочку: ненужный group by )</li><li><a href="https://blog.2ndquadrant.com/tablesample-in-postgresql-9-5-2/">Tablesample In PostgreSQL 9.5</a> by 2ndQuadrant</li><li><a href="https://blog.2ndquadrant.com/tablesample-and-other-methods-for-getting-random-tuples/">Tablesample and Other Methods for Getting Random Tuples</a> by 2ndQuadrant</li><li><a href="https://wiki.postgresql.org/wiki/TABLESAMPLE_Implementation">Tablesample PG wiki</a></li><li><a href="https://stackoverflow.com/questions/14299043/postgresql-pl-pgsql-random-value-from-array-of-values">Выборка одного случайного значения из массива в Postgres, answer by Erwin Brandstetter</a></li><li><a href="http://web.archive.org/web/20080214235745/http://www.powerpostgresql.com/Random_Aggregate">Random_agg — пример написания аггрегационной ф-ии для постгреса аггрегирующей одно случайное значение из выборки.</a></li><li><a href="https://dba.stackexchange.com/questions/96610/sampling-in-postgresql">Sampling in Postgres, answer by Erwin Brandstetter</a></li><li><a href="https://stackoverflow.com/questions/5297396/quick-random-row-selection-in-postgres">Одна из самых полных подборок вариантов построения рандомизированной выборки для Postgres.</a></li><li><a href="https://stackoverflow.com/questions/8674718/best-way-to-select-random-rows-postgresql/8675160">Еще одна мощная подборка с примерами реализаций, так же отличная подборка от Erwin Brandstetter</a></li><li><a href="https://ru.wikipedia.org/wiki/%D0%9B%D0%B8%D0%BD%D0%B5%D0%B9%D0%BD%D1%8B%D0%B9_%D0%BA%D0%BE%D0%BD%D0%B3%D1%80%D1%83%D1%8D%D0%BD%D1%82%D0%BD%D1%8B%D0%B9_%D0%BC%D0%B5%D1%82%D0%BE%D0%B4">Линейный конгруэнтный метод</a> построения случайной последовательности.</li><li><a href="https://docs.ruby-lang.org/en/2.0.0/Array.html#method-i-sample">Ruby arr.sample</a></li></ol><h4>Приложение</h4><p>Код реализации метода sample у массивов в руби:</p><pre>static VALUE<br>rb_ary_sample(int argc, VALUE *argv, VALUE ary)<br>{<br>    VALUE nv, result, *ptr;<br>    VALUE opts, randgen = rb_cRandom;<br>    long n, len, i, j, k, idx[10];<br>    long rnds[numberof(idx)];<br><br>    if (OPTHASH_GIVEN_P(opts)) {<br>        randgen = rb_hash_lookup2(opts, sym_random, randgen);<br>    }<br>    ptr = RARRAY_PTR(ary);<br>    len = RARRAY_LEN(ary);<br>    if (argc == 0) {<br>        if (len == 0) return Qnil;<br>        if (len == 1) {<br>            i = 0;<br>        }<br>        else {<br>            i = RAND_UPTO(len);<br>            if ((len = RARRAY_LEN(ary)) &lt;= i) return Qnil;<br>            ptr = RARRAY_PTR(ary);<br>        }<br>        return ptr[i];<br>    }<br>    rb_scan_args(argc, argv, &quot;1&quot;, &amp;nv);<br>    n = NUM2LONG(nv);<br>    if (n &lt; 0) rb_raise(rb_eArgError, &quot;negative sample number&quot;);<br>    if (n &gt; len) n = len;<br>    if (n &lt;= numberof(idx)) {<br>        for (i = 0; i &lt; n; ++i) {<br>            rnds[i] = RAND_UPTO(len - i);<br>        }<br>    }<br>    k = len;<br>    len = RARRAY_LEN(ary);<br>    ptr = RARRAY_PTR(ary);<br>    if (len &lt; k) {<br>        if (n &lt;= numberof(idx)) {<br>            for (i = 0; i &lt; n; ++i) {<br>                if (rnds[i] &gt;= len) {<br>                    return rb_ary_new2(0);<br>                }<br>            }<br>        }<br>    }<br>    if (n &gt; len) n = len;<br>    switch (n) {<br>      case 0:<br>        return rb_ary_new2(0);<br>      case 1:<br>        i = rnds[0];<br>        return rb_ary_new4(1, &amp;ptr[i]);<br>      case 2:<br>        i = rnds[0];<br>        j = rnds[1];<br>        if (j &gt;= i) j++;<br>        return rb_ary_new3(2, ptr[i], ptr[j]);<br>      case 3:<br>        i = rnds[0];<br>        j = rnds[1];<br>        k = rnds[2];<br>        {<br>            long l = j, g = i;<br>            if (j &gt;= i) l = i, g = ++j;<br>            if (k &gt;= l &amp;&amp; (++k &gt;= g)) ++k;<br>        }<br>        return rb_ary_new3(3, ptr[i], ptr[j], ptr[k]);<br>    }<br>    if (n &lt;= numberof(idx)) {<br>        VALUE *ptr_result;<br>        long sorted[numberof(idx)];<br>        sorted[0] = idx[0] = rnds[0];<br>        for (i=1; i&lt;n; i++) {<br>            k = rnds[i];<br>            for (j = 0; j &lt; i; ++j) {<br>                if (k &lt; sorted[j]) break;<br>                ++k;<br>            }<br>            memmove(&amp;sorted[j+1], &amp;sorted[j], sizeof(sorted[0])*(i-j));<br>            sorted[j] = idx[i] = k;<br>        }<br>        result = rb_ary_new2(n);<br>        ptr_result = RARRAY_PTR(result);<br>        for (i=0; i&lt;n; i++) {<br>            ptr_result[i] = ptr[idx[i]];<br>        }<br>    }<br>    else {<br>       <strong> VALUE *ptr_result;<br>        result = rb_ary_new4(len, ptr);<br>        RBASIC(result)-&gt;klass = 0;<br>        ptr_result = RARRAY_PTR(result);<br>        RB_GC_GUARD(ary);<br>        for (i=0; i&lt;n; i++) {<br>            j = RAND_UPTO(len-i) + i;<br>            nv = ptr_result[j];<br>            ptr_result[j] = ptr_result[i];<br>            ptr_result[i] = nv;<br>        }<br>        RBASIC(result)-&gt;klass = rb_cArray;<br>    }<br>    ARY_SET_LEN(result, n);</strong><br><br>    return result;<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ded79351132" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple sample for Postgres and ruby]]></title>
            <link>https://leshchuk.medium.com/simple-sample-for-postgres-and-ruby-ca44aa689c2c?source=rss-afaaebe85f49------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca44aa689c2c</guid>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[AlekseyL]]></dc:creator>
            <pubDate>Fri, 09 Mar 2018 07:39:34 GMT</pubDate>
            <atom:updated>2018-03-13T12:57:25.971Z</atom:updated>
            <content:encoded><![CDATA[<p>Русская версия статьи: <a href="https://medium.com/@leshchuk/simple-sample-%D0%B2-ruby-%D0%B8-postgres%D0%B5-%D1%80%D1%83%D1%81-6ded79351132">Simple sample в ruby и Postgres’е. (рус)</a></p><h3>Whats inside:</h3><ol><li>An example of a fast <strong>pseudo-random sampling of an array</strong> in ruby and Postgres.</li><li>Comparison between different sampling implementations with a given one. In short <strong>for Postgres </strong>it’s much faster then <strong>order by random()</strong> or <strong>where random &lt; 0.xx</strong>. For ruby its faster for arrays with size greater than 2000 elements and sampling size greater than 10.</li><li>What is the main flaw of the TABLESAMPLE SYSTEM and the TABLESAMPLE SYSTEM_ROWS and how to escape it.</li><li>An example of a random STABLE function</li></ol><p>Through this paper I will state N as a set size, and M as a sample size.</p><h4>Sampling</h4><p>Sampling is a common task in programming.</p><p>Sample can be a consecutive or randomized.</p><p>Sampling functions delivering results directly to a user, must be UX appropriate. This mean that for a given set and sample size, function delivers <strong>same amount</strong> of requested objects<strong> without duplicates</strong>. Imagine pagination with duplicates and variable objects count per page, it would be at least uncomfortable to use such a feed.</p><h4>M-partial sampling</h4><p>Lets implement pseudo-random sampling by splitting a whole set to M equal parts and randomly selecting one element from every part.</p><p><strong>Advantages:</strong></p><ul><li>Don’t need any nested cycles or sortings to remove duplicates, since M-parts are separated by design</li><li>Random() called only M times, it’s significant when N is greater than M</li><li>Result has a fixed size equal to M.</li><li>For small M you can unfold algorithm to a single query, making it lightning-fast for the tuples that doesn’t get TOASTed.</li></ul><p><strong>Disadvantages</strong></p><ul><li>Not all of M combinations can be produced with this method. While a general combinations count is equal to binomial coefficient N!/M!(N-M)!, this subset contains only (N/M) in a power of M combinations, which is less than a binomial coefficient.</li><li>You need to know the N, which is not mandatory for some implementations, like <a href="http://web.archive.org/web/20080214235745/http://www.powerpostgresql.com/Random_Aggregate">random_agg</a> or TABLESAMPLE BERNOULLI.</li><li>M better be less than a N/2, a couple of time less.</li></ul><h4>Ruby</h4><p>Lets compare a ruby native array sample method with a given implementation of suggested algorithm:</p><pre><strong>class Array<br>  def </strong>pseudo_random_sample(<em>count</em>)<br>    result = Array.new(<em>count</em>)<br>    piece_size = length / <em>count<br>    </em>reminder = length - piece_size * <em>count<br>    count</em>.times do |<em>i</em>| <br>      result[<em>i</em>] = ( <em>i &lt; count </em>- 1 ?<br>                  self[rand(piece_size) + <em>i</em>*piece_size] :<br>                  self[rand(piece_size + reminder) + <em>i</em>*piece_size] )<br>    end<br>    result<br><strong>  end<br>end</strong></pre><p>If you look inside sample method sources, you will learn that implementation is splitted between cases: M= 1,2,3, M = N, M ≤ 10 and the last one case when M &gt; 10. Except for M &gt;10 they are highly optimised. The last one case implementation is quite elegant, but it contains a serious flaw: it always clone an original array, doubling memory used.</p><p>For M = 11, N = 100K:</p><pre>Warming up --------------------------------------<br>            .......................<br>Calculating -------------------------------------<br>             classic    3.666k (± 4.8%) i/s   - 18.564k in  5.07s<br>           m-partial    192.859k (± 5.9%) i/s - 967.470k in 5.03s<br>  m-partial+shuffle!    177.411k (± 5.2%) i/s - 893.048k in 5.04s</pre><pre>Comparison:<br>           m-partial:   192859.0 i/s<br>  m-partial+shuffle!:   177410.8 i/s - same-ish<br>             classic:     3666.2 i/s - <strong>52.60x  slower</strong></pre><p>Native sample is <strong>52 times slower than M-partial implementation!</strong></p><p>Of course, with a sample size growth, more time spent in a pure ruby, and the difference is lesser. For an N = 100K they will break even at M ~ 700. Also this is true for a lesser N, for M = 11 a performance breaks even at N = 2000 elements.</p><p>If we go below 11 for an M or below 2000 for an N than <strong>native sample will be</strong> <strong>2–3.5 times faster.</strong></p><h3>PostgreSQL arrays sample.</h3><h4>Consequtive sample</h4><p>If you need a consequtive sample of an array in Postgres you can just use square brackets like this:</p><pre>SELECT user_ids[1:2] FROM docs LIMIT 1;</pre><pre>user_ids    <br>---------------<br> {70049,51869}</pre><p>You must just keep a ≤ b and both of them betwen array bundaries.</p><h4>Random or pseudo random sample</h4><p>There isn’t any builtin arrays function for a random sampling. So now we have two options: call unnest and use a table sampling algorithms, or write custom function. Lets do both and compare performances.</p><h4>Random sampling for tables</h4><p>Here is a complete list of random sampling implementations for tables from the internet discussions and papers:</p><ol><li>TABLESAMPLE ( and tsm_system_rows extention )</li><li>ORDER BY random() LIMIT M</li><li>WHERE random() &lt; 0.xx ( like TABLESAMPLE BERNOULLI )</li><li>+1 Indexed random value column</li><li>Variations around: WHERE id IN ( SELECT random() * id_max FROM generate_series(1, M) ) and so.</li><li>For M = 1 <a href="http://web.archive.org/web/20080214235745/http://www.powerpostgresql.com/Random_Aggregate">random_agg</a>, for M &gt; 1 you will need to rewrite it.</li></ol><h4>Will not work with arrays</h4><p>TABLESAMPLE — doesn’t work with array unnest.</p><p>+1 Indexed random value column — also not for arrays.</p><h4>Will work with arrays</h4><pre><strong>ORDER BY random() LIMIT M</strong></pre><p><strong>This is always the slowest solution</strong>, but it guaranteed with M elements.</p><pre><strong>WHERE random() &lt; M/N</strong></pre><p><strong>Doesn’t guaranteed with M rows</strong>, but skips reordering and searches for duplicates. It’s the fastest solution among those who calls random() N times, like random_agg below. I will use it as a performance marker for both of them.</p><pre><strong>Adaptaion for </strong><a href="http://web.archive.org/web/20080214235745/http://www.powerpostgresql.com/Random_Aggregate"><strong>random_agg</strong></a><strong> for  M &gt; 1</strong></pre><p>It’s possible to rewrite it to M &gt; 1, but it will not be faster then previos variant so I will skip it, since its implementation is not obvious.</p><pre><strong>SELECT arr[random() * arr_length] FROM generate_series(1, M)</strong>.</pre><p>It’s analog to method in <a href="https://www.periscopedata.com/blog/how-to-sample-rows-in-sql-273x-faster">How To Sample Rows in SQL 273X Faster</a>:</p><pre>select * from users<br>where id in (<br>  select round(random() * 21e6)::integer as id<br>  from generate_series(1, 110) <br>)<br>limit 100</pre><p>Nice and fast way but with a general flaw: generated series may contain duplicates! The probability of having at least one duplicate in a sample is tend to one with larger M, starting from probability of ~ 0.5 for M = 2*.</p><p>Row deletion is also a deal breaker for original method.</p><p>It may be used as a sample function for some statistic engine and as a performance marker, it’s obviously the fastest way to deal with M random positions. But it’s not suitable for a direct UX.</p><p>*Probability equals to ( N^M — N!/M!(N-M)! )/N^M</p><h4>Performance</h4><p>Sample functions:</p><pre>-- order by random<br>CREATE OR REPLACE FUNCTION random_sample_obr( bigint[], int ) RETURNS TABLE (id bigint) AS $$<br>  SELECT * FROM unnest($1) ORDER BY random() LIMIT $2;<br>$$ LANGUAGE SQL;</pre><pre>-- less than random<br>CREATE OR REPLACE FUNCTION random_sample_lr( bigint[], int ) RETURNS TABLE (id bigint) AS $$<br>DECLARE<br>  -- probability is same for all set, so it must be evaluated once<br>  probability float := $2::float / cardinality($1);<br>BEGIN<br>  RETURN QUERY SELECT * FROM unnest($1) WHERE random() &lt; probability;<br>END<br>$$ LANGUAGE plpgsql;</pre><pre>--generate series analogue for array<br>CREATE OR REPLACE FUNCTION random_sample_gs( arr bigint[], sample_size int ) RETURNS TABLE (id bigint) AS $$<br>DECLARE<br>  arr_length int := cardinality(arr);<br>  result bigint[];<br>BEGIN<br>  FOR i IN 1..sample_size LOOP<br>    result[i] = arr[floor(random()*arr_length)];<br>  END LOOP;<br>END<br>$$ LANGUAGE plpgsql;</pre><pre>--M-partial sample<br>CREATE OR REPLACE FUNCTION random_sample_mp( arr bigint[], sample_size int ) RETURNS bigint[] AS $$<br>DECLARE<br>  result bigint[];<br>  piece_size int := cardinality(arr) / sample_size;<br>  reminder int := cardinality(arr) - piece_size * sample_size;<br>BEGIN <br>  FOR i IN 1..sample_size LOOP<br>    IF i = sample_size THEN<br>      result[i] := arr[floor((piece_size + reminder)*random() + 1) +         <br>                   (i-1)*piece_size];<br>    ELSE<br>      result[i] := arr[floor(piece_size*random() + 1) + <br>                  (i-1)*piece_size];<br>    END IF;<br> <br>  END LOOP; <br>  RETURN result;<br>END<br>$$ LANGUAGE plpgsql;</pre><p>Measured query:</p><pre>SELECT random_sample_XXX( user_ids, M) as uid, title<br>  FROM &quot;cards&quot; <br>-- random ids from cards, generated outside time measurement<br>  WHERE &quot;cards&quot;.&quot;id&quot; IN (...)</pre><p>All queries ‘normalized’ by cleared query:</p><pre>SELECT title FROM &quot;cards&quot; WHERE &quot;cards&quot;.&quot;id&quot; IN (...)</pre><p>So its very close to a pure functions time measurement.</p><p>I ran performance test for different N, different M, and different number of ids, but as expected: an N is a major factor, so I’ll fix M to 5 and ids count to 10 and step over N in resulting table.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98f3eeeac41f55ced3616e72068aab52/href">https://medium.com/media/98f3eeeac41f55ced3616e72068aab52/href</a></iframe><h4>STABLE random_sample</h4><p>In Postgres you can declare functions as <a href="https://www.postgresql.org/docs/10/static/xfunc-volatility.html">STABLE, IMMUTABLE and VOLATILE</a>. Default category is VOLATILE. It means than calls to this function can’t be optimized and sometimes it can lead to unintended behaviour.</p><p>Lets review this query:</p><pre>SELECT * FROM docs<br>JOIN users ON users.id = ANY( random_sample(user_ids, M) ) <br>WHERE docs.id = ID;</pre><p>Desired and expected behavior is to call random_sample once, get a sample and select all users for it. But by default Postgres will interpret this query similarly to this one:</p><pre>SELECT * FROM docs<br>JOIN users ON random()<br>WHERE docs.id = ID;</pre><p>It will call random_sample <strong>for all rows from users table</strong>, because random() declared as VOLATILE, and this is default behaviuor for a custom functions declaration.</p><p>You can declare VOLATILE function as STABLE, and postgres planner may optimize calls to it. <strong>May doesn’t mean it must! </strong>Tricking planner is dangerous thing to do.</p><p>Thats why we may need custom random() STABLE function. We don’t need it to be cryptographically secure, so it may be defined like this:</p><pre>CREATE FUNCTION random_stable( prev bigint ) RETURNS int AS $$<br>BEGIN<br>   RETURN (prev * 1103515245 + 12345) / 65536 % 32768; <br>END;<br>$$ LANGUAGE plpgsql IMMUTABLE;</pre><p>After that all random() calls need to be replaced with:</p><pre>random_value := random_stable(random_value);</pre><p>But to get stable sequence per single transaction we must init first random value with a stable “random” value, it can be done like this:</p><pre>random_value := random_stable( extract( microseconds FROM  current_timestamp) );</pre><p>Now you get a random sequence, which is truly stable inside a transaction and if a planner defy your hint, still all results will be correct.</p><h4>ORM + DB optimizations</h4><p>There are couple more optimizations to consider at the junction of DB and ORM: unfolding query for small M, pregenerating random sequence in ORM, and implementing original ruby sample idea.</p><p>I will start with the last one, as I mentioned before the main problem for the ruby elegant sampling solution is doubling of the memory used. But inside Postgres function, we already dealing with a copy of an array, so we already pay the debt and may freely change incoming array, and return its sample:</p><pre>CREATE OR REPLACE FUNCTION random_sample_ruby_way( arr bigint[], sample_size int ) RETURNS bigint[] AS $$<br>DECLARE<br>  current_rand bigint;<br>  j int := 0;<br>  arr_size int := cardinality(arr);<br>  swapper bigint := 0;<br>BEGIN<br>  current_rand := extract( milliseconds FROM  current_timestamp)::int;<br> <br>  FOR i IN 1..sample_size LOOP<br>    current_rand := random_stable(current_rand);<br>    j := current_rand % ( arr_size - i ) + i;  <br>    swapper := arr[j];<br>    arr[j] := arr[i];<br>    arr[i] := swapper;<br>  END LOOP; <br>  RETURN arr[:sample_size];<br>END<br>$$ LANGUAGE plpgsql STABLE;</pre><p>so it has a speed of a M-partial algorithm, without any drawbacks and tradeoffs. Nice!</p><p>But lets go more further and skip any random calls inside query, by pregenerating one inside ORM, so the ruby way realization will transform to:</p><pre>CREATE OR REPLACE FUNCTION random_sample_pregenerated_sequence( arr bigint[], random_arr int[] ) RETURNS bigint[] AS $$<br>DECLARE<br>  j int := 0;<br>  arr_size int := cardinality(arr);<br>  sample_size int := cardinality(random_arr);<br>  swapper bigint := 0;<br>BEGIN<br> <br>  FOR i IN 1..sample_size LOOP<br>    j := random_arr[i] % ( arr_size - i ) + i;  <br>    swapper := arr[j];<br>    arr[j] := arr[i];<br>    arr[i] := swapper;<br>  END LOOP; <br>  RETURN arr[:sample_size];<br>END<br>$$ LANGUAGE plpgsql STABLE;</pre><h4>M-Partial QUERY unfolded</h4><p>If array is small enough than row doesn’t get TOASTed. As PG manuals states:</p><blockquote>The TOAST management code is triggered only when a row value to be stored in a table is wider than TOAST_TUPLE_THRESHOLD bytes (normally 2 kB).</blockquote><p>For array of bigints its less than 250 elems. Don’t forget that row data contains not only pure array, but usually more of an user and system data, so in real use cases it better be less than 200 elements.</p><p>For such cases super fast way (but also super ugliest :)) is to unfold query with ORM to something like this:</p><pre>SELECT *, ARRAY[<br>   user_ids[30776 % (cardinality(user_ids)/M)],<br>   user_ids[12021 % (cardinality(user_ids)/M) +   <br>           cardinality(user_ids) * i / M] <br>   ...<br>   user_ids[5410 % (cardinality(user_ids)/M + <br>                     cardinality(user_ids) % M ) +   <br>           cardinality(user_ids) * (M-1)/ M]<br>] as sample <br>FROM docs;</pre><p>Here is a final performance comparison table with STABLE random functions normalized by fastest*:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4fb12b778799a7825e67d64b1ff1d5ae/href">https://medium.com/media/4fb12b778799a7825e67d64b1ff1d5ae/href</a></iframe><p>*Except for generate series analogue cause it’s not fully correct and used just as performance marker.</p><h4>Sample from TABLESAMPLE</h4><p>TABLESAMPLE SYSTEM and TABLESAMPL ESYSTEM_ROWS are the most perfomant way in Postgres to deliver table sampling, but they are suffering from one serious flaw: they deliver sample by pages and and it’s quite often became a sequential samples, especially for small M.</p><p>On table size of a 1.1M for query:</p><pre>SELECT array_agg(id) FROM docs TABLESAMPLE SYSTEM_ROWS(5);</pre><p>You easily can get results like this:</p><pre>{2083068,2083069,2083070,2083071,2083072}</pre><pre>OR</pre><pre>{1168539,1168541,1168542,1168547,1168551}</pre><p>And this is not what you expected while reaching for a random sampling.</p><p>But you can take sample from TABLESAMPLE with a trick like this:</p><pre>SELECT random_sample(array_agg(id), 10) <br>FROM cards TABLESAMPLE SYSTEM(1);</pre><p>It’s superfast, doesn’t suffer from “paginated” sampling and UX appropriate, sweet!</p><h3>Appendix</h3><h4>Sample source</h4><p>A ruby native Array sample method source, with a case M &gt; 10 bolded :</p><pre>static VALUE<br>rb_ary_sample(int argc, VALUE *argv, VALUE ary)<br>{<br>    VALUE nv, result, *ptr;<br>    VALUE opts, randgen = rb_cRandom;<br>    long n, len, i, j, k, idx[10];<br>    long rnds[numberof(idx)];</pre><pre>    if (OPTHASH_GIVEN_P(opts)) {<br>        randgen = rb_hash_lookup2(opts, sym_random, randgen);<br>    }<br>    ptr = RARRAY_PTR(ary);<br>    len = RARRAY_LEN(ary);<br>    if (argc == 0) {<br>        if (len == 0) return Qnil;<br>        if (len == 1) {<br>            i = 0;<br>        }<br>        else {<br>            i = RAND_UPTO(len);<br>            if ((len = RARRAY_LEN(ary)) &lt;= i) return Qnil;<br>            ptr = RARRAY_PTR(ary);<br>        }<br>        return ptr[i];<br>    }<br>    rb_scan_args(argc, argv, &quot;1&quot;, &amp;nv);<br>    n = NUM2LONG(nv);<br>    if (n &lt; 0) rb_raise(rb_eArgError, &quot;negative sample number&quot;);<br>    if (n &gt; len) n = len;<br>    if (n &lt;= numberof(idx)) {<br>        for (i = 0; i &lt; n; ++i) {<br>            rnds[i] = RAND_UPTO(len - i);<br>        }<br>    }<br>    k = len;<br>    len = RARRAY_LEN(ary);<br>    ptr = RARRAY_PTR(ary);<br>    if (len &lt; k) {<br>        if (n &lt;= numberof(idx)) {<br>            for (i = 0; i &lt; n; ++i) {<br>                if (rnds[i] &gt;= len) {<br>                    return rb_ary_new2(0);<br>                }<br>            }<br>        }<br>    }<br>    if (n &gt; len) n = len;<br>    switch (n) {<br>      case 0:<br>        return rb_ary_new2(0);<br>      case 1:<br>        i = rnds[0];<br>        return rb_ary_new4(1, &amp;ptr[i]);<br>      case 2:<br>        i = rnds[0];<br>        j = rnds[1];<br>        if (j &gt;= i) j++;<br>        return rb_ary_new3(2, ptr[i], ptr[j]);<br>      case 3:<br>        i = rnds[0];<br>        j = rnds[1];<br>        k = rnds[2];<br>        {<br>            long l = j, g = i;<br>            if (j &gt;= i) l = i, g = ++j;<br>            if (k &gt;= l &amp;&amp; (++k &gt;= g)) ++k;<br>        }<br>        return rb_ary_new3(3, ptr[i], ptr[j], ptr[k]);<br>    }<br>    if (n &lt;= numberof(idx)) {<br>        VALUE *ptr_result;<br>        long sorted[numberof(idx)];<br>        sorted[0] = idx[0] = rnds[0];<br>        for (i=1; i&lt;n; i++) {<br>            k = rnds[i];<br>            for (j = 0; j &lt; i; ++j) {<br>                if (k &lt; sorted[j]) break;<br>                ++k;<br>            }<br>            memmove(&amp;sorted[j+1], &amp;sorted[j], sizeof(sorted[0])*(i-j));<br>            sorted[j] = idx[i] = k;<br>        }<br>        result = rb_ary_new2(n);<br>        ptr_result = RARRAY_PTR(result);<br>        for (i=0; i&lt;n; i++) {<br>            ptr_result[i] = ptr[idx[i]];<br>        }<br>    }<br>    else {<br>       <strong> VALUE *ptr_result;<br>        result = rb_ary_new4(len, ptr);<br>        RBASIC(result)-&gt;klass = 0;<br>        ptr_result = RARRAY_PTR(result);<br>        RB_GC_GUARD(ary);<br>        for (i=0; i&lt;n; i++) {<br>            j = RAND_UPTO(len-i) + i;<br>            nv = ptr_result[j];<br>            ptr_result[j] = ptr_result[i];<br>            ptr_result[i] = nv;<br>        }<br>        RBASIC(result)-&gt;klass = rb_cArray;<br>    }<br>    ARY_SET_LEN(result, n);</strong></pre><pre>    return result;<br>}</pre><h4>Links</h4><ol><li><a href="https://stackoverflow.com/questions/24851986/return-random-no-repeating-rows-from-a-table-postgresql">Return random, no-repeating rows from a table — PostgreSQL</a></li><li><a href="https://www.periscopedata.com/blog/how-to-sample-rows-in-sql-273x-faster">How To Sample Rows in SQL 273X Faster</a></li><li><a href="https://blog.2ndquadrant.com/tablesample-in-postgresql-9-5-2/">Tablesample In PostgreSQL 9.5</a> by 2ndQuadrant</li><li><a href="https://blog.2ndquadrant.com/tablesample-and-other-methods-for-getting-random-tuples/">Tablesample and Other Methods for Getting Random Tuples</a> by 2ndQuadrant</li><li><a href="https://wiki.postgresql.org/wiki/TABLESAMPLE_Implementation">Tablesample PG wiki</a></li><li><a href="https://stackoverflow.com/questions/14299043/postgresql-pl-pgsql-random-value-from-array-of-values">PostgreSQL PL/pgSQL random value from array of values, answer by Erwin Brandstetter</a></li><li><a href="http://web.archive.org/web/20080214235745/http://www.powerpostgresql.com/Random_Aggregate">Random_agg — aggregation function for of one random element.</a></li><li><a href="https://dba.stackexchange.com/questions/96610/sampling-in-postgresql">Sampling in Postgres, answer by Erwin Brandstetter</a></li><li><a href="https://stackoverflow.com/questions/5297396/quick-random-row-selection-in-postgres">Quick random row selection in Postgres</a></li><li><a href="https://stackoverflow.com/questions/8674718/best-way-to-select-random-rows-postgresql/8675160">Best way to select random rows, with nice summary by Erwin Brandstetter</a></li><li><a href="https://en.wikipedia.org/wiki/Linear_congruential_generator">Linear congruential generator</a></li><li><a href="https://docs.ruby-lang.org/en/2.0.0/Array.html#method-i-sample">Ruby arr.sampe source</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca44aa689c2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[От Action к Any]]></title>
            <link>https://leshchuk.medium.com/%D0%BE%D1%82-action-%D0%BA-any-b51f8c202ea3?source=rss-afaaebe85f49------2</link>
            <guid isPermaLink="false">https://medium.com/p/b51f8c202ea3</guid>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[actioncable]]></category>
            <category><![CDATA[anycable]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[actionable-insights]]></category>
            <dc:creator><![CDATA[AlekseyL]]></dc:creator>
            <pubDate>Wed, 20 Dec 2017 10:36:10 GMT</pubDate>
            <atom:updated>2017-12-20T10:40:48.067Z</atom:updated>
            <content:encoded><![CDATA[<p>English version: <a href="https://medium.com/@leshchuk/from-action-to-any-1e8d863dd4cf">From Action To Any</a></p><p>Подкапотные нюансы AnyCable для мигрирующих с ActionCable.</p><p>Что будет интересного:</p><ul><li>Как можно посчитать количество пользователей онлайн в ActionCable и почему это сломается в AnyCable</li><li>Чем отличается current_user в базовом классе Connection при использовании AnyCable от ActionCable.</li><li>Почему AnyCable гарантировано ломает devise при использовании Rails сессии и как с этим быть.</li><li>Чем отличается stop_all_streams в AnyCable от своего аналога в ActionCable</li><li>Как разорвать соединение извне в ActionCable и как это можно сделать AnyCable</li><li>Где была и куда делась проверка заголовка Origin в AnyCable.</li></ul><p>Это небольшое мемо будет интересно для тех кто хочет копнуть на полштыка глубже в теме ActionCable в контексте его альтернативы AnyCable.</p><blockquote>Обращаю внимание читателя на то, что все описанные отличия AnyCable от ActionCable актуальны для версии anycable-rails <a href="https://github.com/anycable/anycable-rails/commit/ba8efacf613945e05d9fa7ecdf1bc8d4067d92bb">0.5.2</a>, anycable <a href="https://github.com/anycable/anycable/commit/b3ddc9b1dce01f06e84fbde0c6519fa500d41c81">0.5.0</a>, и actioncable 5.1.4! Многое из указанного уже вынесено в issue или будет вынесено в ближайшее время и в скором времени будет исправлено или изменено.</blockquote><h4>Введение</h4><p>Для тех кто не в курсе: <a href="http://guides.rubyonrails.org/action_cable_overview.html">ActionCable</a> это подсистема фреймворка Ruby on Rails для реализации realtime web приложений. <a href="http://anycable.io/">AnyCable</a> представляет собой высокопроизводительную альтернативу ActionCable с максимально возможным сохранением экосистемы рельс и ActionCable. Для тех у кого есть вопросы зачем менять родное шило на чужое мыло отвечают три следующих сравнительных картинки .</p><p>Используемой памяти:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PiFjvwfhutGVLwlRw_eCLQ.png" /><figcaption><strong>Benchmark:</strong> handle 20 thousand idle clients to the server (no subscriptions, no transmissions). Источник: <a href="https://evilmartians.com/chronicles/anycable-actioncable-on-steroids">AnyCable — ActionCable на стероидах</a></figcaption></figure><p>Загрузки ядер:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*EqOhAJTc2lxa4Cpn0ka4Dg.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*4ckgrgnux83tHvi-Axs67A.gif" /><figcaption>ActionCable VS AnyCable <a href="https://github.com/hashrocket/websocket-shootout">WebSocket Shootout </a>benchmark, источник: <a href="https://evilmartians.com/chronicles/anycable-actioncable-on-steroids">AnyCable — ActionCable на стероидах</a></figcaption></figure><p>Задержки сообщений при росте числа подключений:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-m5RoP-qtUxbN_1M8aEM3A.png" /><figcaption>Задержка броадкастинга в секундах от количества подключений, источник: <a href="https://evilmartians.com/chronicles/anycable-actioncable-on-steroids">AnyCable — ActionCable на стероидах</a></figcaption></figure><p>Так или иначе, вот три причины, каждая из которых уже сама по себе достаточна для того, чтобы задуматься о внедрении AnyCable на место ActionCable.</p><p>Дальше встает вопрос цены такого внедрения, что мы приобретем наглядно видно на трех приведенных сравнениях, что мы теряем и какие сложности у нас могут возникнуть на пути внедрения?</p><p>Вот хорошая табличка текущей совместимости обощенная <a href="https://github.com/palkan">Владимиром Дементьевым</a>, автором AnyCable:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59b289da6a4f0a00460d37a47ca6f45b/href">https://medium.com/media/59b289da6a4f0a00460d37a47ca6f45b/href</a></iframe><p>Но помимо этой таблички есть еще кое-какие нюансы, которые стоит понимать, при замене ActionCable на AnyCable.</p><p>Начнем со стороны того, что никак не цепляет такая перемена: фронтэнда.</p><h4>Front-end</h4><p>Со стороны фронта изменения в общем-то отсутствуют, ws-сервера AnyCable полностью совеместимы сейчас с кодом ActionCable на фронте.</p><h4>Back-end</h4><p>Вот тут все немножко сложнее. Для начала можем посмотреть на архитектуру, так сказать, с высоты:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*Uc_GdznX3eS0AYEHybhOsA.jpeg" /><figcaption>Сравнение архитектур AnyCable VS ActionCable. Источник: <a href="https://github.com/anycable/anycable-rails">anycable-rails repo</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wXuFDSv7dcxtJQQgAfP8TQ.png" /><figcaption>Более подробно архитектура AnyCable. Источник: <a href="https://evilmartians.com/chronicles/anycable-actioncable-on-steroids">ActionCable on steroids</a></figcaption></figure><p>Что мы видим: вебсокет сервер вынесен отдельно, ActionCable заменен на Anycable RPC с вызовом по <a href="https://grpc.io/">gRPC</a>.</p><h4>Minus Rack middleware</h4><p>Если проявить внимательность, уже на этом этапе можно предугадать первую проблему, с которой придется столкнуться при переводе приложения с ActionCable на AnyCable: несмотря на загрузку Rails приложения, AnyCable это RPC сервис, а ActionCable это Rack based сервер. А это значит, что все Rack-middleware недоступно в AnyCable из коробки! Если вы хотите, что-то использовать вам придется реализовывать это через дополнительные обертки/костыли.</p><p>Самый простой и яркий пример, который коснется практически всех, кто будет переводить свое приложение с ActionCable: недоступно Warden middleware, это значит, что если у вас была аутентификация с использованием devise в ActionCable, она сломается. <a href="https://stackoverflow.com/questions/38470463/rails-devise-action-cable">Stackoverflow приводит</a>, например, вот такой способ использования devise совместно с ActionCable:</p><pre>verified_user = env[&#39;warden&#39;].user</pre><p>В AnyCable это бессмысленно, потому что middle нет и env[&#39;warden&#39;] == nil.</p><p>Как это можно подлечить? Например так:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a42fcdfe6aa50bbaa28437e207f1f08e/href">https://medium.com/media/a42fcdfe6aa50bbaa28437e207f1f08e/href</a></iframe><h4>gRPC и некоторые некомсомольские методы</h4><p>Еще одним следствием вынесения поддержания сокетов в отдельный сервер и упрощение Rack приложения до gRPC стало то, что многие функции стали работать в пассивном режиме — всего лишь выставляя значения, которые будут возвращены в ws-server, тогда как в исходном ActionCable они непосредственно осуществляли соответствующие действия.</p><p>Например, метод stop_all_streams в исходном варианте непосредственно отписывал стримы от подписок, и после вызова можно считать, что команда отписаться уже ушла на редис, в случае с AnyCable до тех пор пока не произойдет возврата из вызова gRPC в ws-сервер процедура отписки стримов не запустится.</p><p>В целом знание этой особенности реализации может быть актуально в двух случаях: если после вызова stop_all_streams далее по коду выкинет эксепшен, то поведение ActionCable будет отличным от AnyCable, и это может помочь быстрее найти проблему на стыке AnyCable и ws-сервера, если таковая возникнет.</p><h4>Long live Connection!</h4><p>Продолжаем копаться в классе ActionCable::Connection. В классическом исполнении ActionCable инстансы класса ActionCable::Connection живут все время соединения! Как ни странно, но в документации акцент этот пропущен, основной акцент в документации делается на то что объекты каналов живут долго, но собственно они живут внутри как раз объекта Connection, в коде ActionCable::Channel есть на этот счет отсылка:</p><blockquote><em>Channel instances are long-lived. A channel object will be instantiated </em><strong><em>when </em></strong><em>the cable consumer becomes a subscriber, and then lives </em><strong><em>until </em></strong><em>the consumer disconnects.</em></blockquote><blockquote><em>Long-lived channels (</em><strong><em>and connections</em></strong><em>) also mean you&#39;re responsible for ensuring that the data is fresh. If you hold a reference to a user record, but the name is changed </em><strong><em>while </em></strong><em>that reference is held, you may be sending stale data </em><strong><em>if </em></strong><em>you don&#39;t take precautions to avoid it.</em></blockquote><p>Вот тут мы пришли к следующему отличию AnyCable: в AnyCable нет долгоживущих объектов! Все объекты создаются только на время вызова по gRPC, и сериализуются/десериализуются посредством <a href="https://github.com/rails/globalid">globalid gem</a>’а.</p><p>Таким образом, все ActiveRecord объекты, которые были привязаны в ActionCable::Connection через вызов identified_by, теперь релоадятся перед использованием, т.е. то что раньше было просто current_user, на самом деле теперь всегда current_user.reload.</p><p>С одной стороны это удобно: у объекта всегда актуальное на момент вызова состояние. С другой, теперь каждый вызов методов Connection/Channel из JS может приводить к дополнительным обращениям к БД, по числу таких idetified_by объектов, и в ряде случаев, имеет смысл отказаться от использования ActiveRecord объектов заменив их на простые структуры.</p><h4>Броадкастну, а в ответ тишина…</h4><p>Продолжаем по прежнему копаться в классе Connection и его отличиях от базового варианта. Теперь нас интересуют InternalChannel и RemoteConnections ( оба находятся в namespace ActionCable::Connection). Каждый создаваемый на бекенде объект коннекшен не только контролирует подписку пользователя на каналы, но и сам дополнительно создает и подписывается на внутренний канал сообщений, который в частности используется для принудительного разрыва соединения извне, например, из основного Rails приложения.</p><p>Если мы запустим обычный демо пример action cable, который приводится в описании ActionCable, присоединимся из двух браузеров к паре каналов и после этого посмотрим как дела в Redis.pubsub, мы увидим вот такой вывод:</p><pre>2.4.1 :020 &gt; redis.pubsub(&#39;channels&#39;)</pre><pre> =&gt; [&quot;action_cable/Z2lkOi8vYWN0aW9uY2FibGUtZXhhbXBsZXMvVXNlci8x&quot;, <br>&quot;messages:1:comments&quot;, <br>&quot;messages:2:comments&quot;, <br>&quot;_action_cable_internal&quot;, &quot;action_cable/Z2lkOi8vYWN0aW9uY2FibGUtZXhhbXBsZXMvVXNlci8z&quot;]</pre><p>Где каналы с префиксом messages — это каналы чат комнат, которые и приводятся в коде демо-приложения, а каналы с префиксом action_cable/ — это внутренние каналы соединений, о которых было сказано выше. Если мы запустим AnyCable приложение и попробуем заглянуть в pubsub redis’а то мы увидим там только одну очередь сообщений, по умолчанию она называется __anycable__!</p><p>На что влияет такая реализация? Ну во-первых пропускная способность всех ваших кабелей теперь зависит от пропускной способности одной очереди pubsub в редисе. Во-вторых полезные советы <a href="https://stackoverflow.com/questions/36106542/how-do-i-find-out-who-is-connected-to-actioncable?noredirect=1&amp;lq=1">как определить кто присоединен к вашим сокетам</a> и <a href="https://stackoverflow.com/questions/32905259/actioncable-how-to-display-number-of-connected-users/47595445#47595445">сколько их</a>, стали теперь вредными, в смысле, нерабочими.</p><p>Ну и возвращаясь к теме заголовка, если мы заглянем в код класса RemoteConnections, чтобы подсмотреть как отключаются связи извне мы увидим:</p><pre>ActionCable.server<br>           .remote_connections<br>           .where(current_user: User.find(1))<br>           .disconnect</pre><p>и в методе дисконнект:</p><pre>server.broadcast internal_channel, type: <strong>&quot;disconnect&quot;</strong></pre><p>Таким образом в ActionCable пройдет сообщение disconnect и соединение закроется, но в AnyCable каналов таких нет, напомню в anycable у нас только одна очередь __anycable__, и этот броадкаст молча уйдет в молоко.</p><p>В общем как и говорила нам табличка совместимости:</p><blockquote>Disconnect remote clients : —</blockquote><p>Как в итоге разорвать соединение извне в AnyCable? Без внесения изменений в ws-сервер, в общем-то, нет гарантированного способа выборочно разорвать соединение из основного rails-приложения, есть только ненадежный: допилить на front-end’е класс канала и отправить на такой доработанный класс специальное сообщение, которое заставит сокет пересоединиться, в чем мы ему можем с удовольствием отказать. Если по каким-то причинам JS проигнорирует наше сообщение, придется ждать или обновления вашего любимого варианта AnyCable ws-сервера, или на худой конец его перезапуска.</p><h4>Пара слов про конфиг</h4><p>Про конфиг ActionCable можно <a href="http://guides.rubyonrails.org/action_cable_overview.html#configuration">почитать в официальном гайде</a>, в двух словах в config/cable.yml лежат настройки pubsub адаптера, остальные можно вписать через config.action_cable.</p><p>Про конфигурацию Anycable <a href="https://github.com/anycable/anycable-rails#configuration">есть кратко в официальном репозитории</a> Основные отличия:</p><ul><li>Не используется cable.yml для своих настроек, во-первых потому что pubsub адаптера как такового на уровне gRPC-сервиса нет и в нем нет потребности, потому что на сообщения подписывается непосредственно ws-сервер, а во-вторых потому что для целей броадкастинга используется только redis его можно только настроить, но выбрать вместо него другой движок для pubsub, например postgreSQL, нет возможности*.</li><li>Для заполнения настроек используется гем <a href="https://github.com/palkan/anyway_config">anyway_config</a>, так что настройки можно выставить и через окружение, и через config/anycable.yml, и вообще через вызов Anycable.configure.</li></ul><p>Также подробнее про связь настроек в config/anycable.yml с параметрами запуска ws-сервера можно прочитать в комментариях к дефолтным настройкам config/anycable.yml добавленным в генератор с версии anycable-rails 0.5.2.</p><p>*Речь про текущую версию AnyCable и anycable-rails ( 0.5.2 ), добавление других pubsub адаптеров <a href="https://github.com/anycable/anycable/issues/2">указано в планах и обсуждается</a></p><h4>Cross Site WebSocket Hijacking (CSWSH).</h4><p>Основной способ защиты от кроссайт подписки на вебсокеты — проверка заголовка Origin, его цепляет браузер в обязательном порядке, и только очень редкая экзотика типа опасных расширений браузера, использование нешифрованного ws соединения и пр. допускают возможность обмана проверки заголовка Origin, но в таких случая сама сессия уже с большой долей вероятности может быть скомпрометирована.</p><p>В контексте AnyCable это проявляется на старте ws-server’а, ему указываются заголовки, которые он будет передавать на gRPC сервис:</p><pre>-headers=cookie,x-api-token,<strong>origin</strong></pre><p>Как видно можно разрешить передавать куки для определения сессии и origin для его проверки. Но в отличе от ActionCable, в Anycable gRPC отсутствует встроенная проверка (<strong>allow_request_origin?</strong>):</p><pre><em># </em><strong><em>ActionCable</em></strong><em>::Connection::Base<br># Called by the server </em><strong><em>when </em></strong><em>a new WebSocket connection is established. This configures the callbacks intended for overwriting by the user.<br># This method should not be called directly -- instead rely upon on the #</em><strong>connect</strong><em> (and #</em><strong>disconnect</strong><em>) callbacks.</em></pre><pre><strong>def </strong>process <em>#</em><strong><em>:nodoc:<br>  </em></strong>logger.info started_request_message<br>  <strong>if </strong>websocket.possible? &amp;&amp; <strong>allow_request_origin?</strong><br>    respond_to_successful_request<br>  <strong>else<br>    </strong>respond_to_invalid_request<br>  <strong>end<br>end</strong></pre><p>Проверку origin легко можно вернуть в приложение самостоятельно, используя вызов allow_request_origin? и <a href="http://guides.rubyonrails.org/action_cable_overview.html#allowed-request-origins">настройки ActionCable</a>:</p><pre>config.action_cable.allowed_request_origins = [&#39;<a href="http://rubyonrails.com&/#39;">http://rubyonrails.com&#39;</a>, %r{<a href="http://ruby.*/">http://ruby.*</a>}]</pre><p>Или же переложить проверку на плечи nginx.</p><h4>Заключение</h4><p>В целом, отличия реализации AnyCable являются не более чем легкими особенностями, а никак не заметными недостатками, которые могут как-то повлиять на решение о внедрении AnyCable.</p><p><em>Мои благодарности </em><a href="https://github.com/palkan"><em>Владимиру Дементьеву</em></a><em> автору AnyCable за сам гем и замечания к данной статье.</em></p><h3>Ссылки</h3><h4>ActionCable:</h4><ol><li><a href="http://guides.rubyonrails.org/action_cable_overview.html">ActionCable guide</a></li><li>Ответы на вопросы <a href="https://stackoverflow.com/questions/36106542/how-do-i-find-out-who-is-connected-to-actioncable?noredirect=1&amp;lq=1">как определить кто присоединен к вашим сокетам</a> и <a href="https://stackoverflow.com/questions/32905259/actioncable-how-to-display-number-of-connected-users/47595445#47595445">сколько их</a></li><li><a href="https://www.sitepoint.com/create-a-chat-app-with-rails-5-actioncable-and-devise/">Chat app rails 5 + ActionCable + devise</a></li><li><a href="https://github.com/rails/actioncable-examples/">ActionCable examples</a></li></ol><h4>Anycable:</h4><ol><li><a href="https://evilmartians.com/chronicles/anycable-actioncable-on-steroids">AnyCable — ActionCable на стероидах</a></li><li><a href="http://anycable.io/">Anycable.io</a></li><li><a href="https://github.com/anycable">Anycable на гитхабе</a></li></ol><h4>Безопасность сокетов:</h4><ol><li><a href="https://www.owasp.org/index.php/Testing_WebSockets_(OTG-CLIENT-010)">OWASP проверка сокетов</a> на предмет разных угроз в том числе кроссайтового подключения</li><li><a href="https://www.theseus.fi/bitstream/handle/10024/113390/Harri+Kuosmanen+-+Masters+thesis+-+Security+Testing+of+WebSockets+-+Final.pdf?sequence=1">Большое и подробное мемо</a> на тестирование Вебсокетов на безопасность от горячих финских парней, в том числе по вопросу Crossite ws Hijacking</li><li>Еще про кроссайтовые<a href="https://www.christian-schneider.net/CrossSiteWebSocketHijacking.html"> сокеты и как уберечься от Кристиана Шнайдера.</a></li><li>Ответы на security.stackexchange.com: <a href="https://security.stackexchange.com/questions/76816/preventing-csrf-attacks-against-websocket-communications">Preventing CSRF against Websockets</a> и <a href="https://security.stackexchange.com/questions/115716/is-the-origin-header-really-useful-for-securing-a-websocket">Is Origin header useful for websocket protection</a>.</li><li>Как <a href="https://stackoverflow.com/questions/30144233/how-to-set-websocket-origin-header-from-javascript">подделать ориджин в JS</a> ( ну в общем практически никак, либо куки не прилипнут, либо ориджин будет исходный)</li><li>Еще статья <a href="https://gist.github.com/subudeepak/9897212">про безопасность WS с обсуждениями</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b51f8c202ea3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Action to Any]]></title>
            <link>https://leshchuk.medium.com/from-action-to-any-1e8d863dd4cf?source=rss-afaaebe85f49------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e8d863dd4cf</guid>
            <category><![CDATA[actioncable]]></category>
            <category><![CDATA[anycable]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[websocket]]></category>
            <dc:creator><![CDATA[AlekseyL]]></dc:creator>
            <pubDate>Wed, 20 Dec 2017 10:33:12 GMT</pubDate>
            <atom:updated>2018-03-07T10:35:03.962Z</atom:updated>
            <content:encoded><![CDATA[<p>Русская версия: <a href="https://medium.com/@leshchuk/%D0%BE%D1%82-action-%D0%BA-any-b51f8c202ea3">От Action к Any</a></p><p>Internal aspects you may notice while migrating from ActionCable to AnyCable</p><p>What’s inside:</p><ul><li>How to count online users in ActionCable and why it would break in AnyCable</li><li>Small differences between current_users defined by identified_by in Connection::Base class.</li><li>Why AnyCable will break your devise authentication and how to fix it.</li><li>What’s the difference between stop_all_streams call in AnyCable and ActionCable</li><li>How to stop connection from the outside with ActionCable, and what to do in AnyCable.</li><li>What happens with cross-origin security in AnyCable comparing to ActionCable.</li></ul><p>This little memo will be useful if you want to dig a little deeper into understanding ActionCable and AnyCable realizations compared to each other.</p><blockquote>Pay attention described issues are actual only for next gem versions: anycable-rails <a href="https://github.com/anycable/anycable-rails/commit/ba8efacf613945e05d9fa7ecdf1bc8d4067d92bb">0.5.2</a>, anycable <a href="https://github.com/anycable/anycable/commit/b3ddc9b1dce01f06e84fbde0c6519fa500d41c81">0.5.0</a> and actioncable 5.1.4! This may change in a nearest perspective.</blockquote><h4>Introduction</h4><p>For those who lately wake up from cryosleep and missed everything: <a href="http://guides.rubyonrails.org/action_cable_overview.html">ActionCable</a> is a part of Ruby on rails framework delivering realtime web functionality based on WebSocket. <a href="http://anycable.io/">AnyCable</a> is high perfomance polyglot alternative to ActionCable with the aim of a maximum compatibility and the lowest possible code changes during its adaptation in place of ActionCable. Does it actually tradeoff or pure win?</p><p>Just look below for real measurements done by <a href="https://github.com/palkan">Vladimir Dementyev</a> creater of AnyCable and see yourself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PiFjvwfhutGVLwlRw_eCLQ.png" /><figcaption><strong>Benchmark:</strong> handle 20 thousand idle clients to the server (no subscriptions, no transmissions). from: <a href="https://evilmartians.com/chronicles/anycable-actioncable-on-steroids">ActionCable on steroids</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*EqOhAJTc2lxa4Cpn0ka4Dg.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*4ckgrgnux83tHvi-Axs67A.gif" /><figcaption>ActionCable VS Anycable running <a href="https://github.com/hashrocket/websocket-shootout">WebSocket Shootout </a>benchmark. ( from <a href="https://evilmartians.com/chronicles/anycable-actioncable-on-steroids">ActionCable on steroids</a> )</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-m5RoP-qtUxbN_1M8aEM3A.png" /><figcaption>broadcast perfomance in seconds per connections count ( from <a href="https://evilmartians.com/chronicles/anycable-actioncable-on-steroids">ActionCable on steroids</a> )</figcaption></figure><p>So now you have at least three strong reasons to switch from ActionCable to AnyCable. Let’s see if there is any reason against such change.</p><p>Here is a nice compatibility table from the AnyCable repo:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59b289da6a4f0a00460d37a47ca6f45b/href">https://medium.com/media/59b289da6a4f0a00460d37a47ca6f45b/href</a></iframe><p>But except for this table, there are couple nuances, which you may notice while migrating toward AnyCable. Let’s start with a simple: front-end.</p><h4>Front-end</h4><p>Good news everyone: nothing changed at the front-end! AnyCable is fully compartible from the front-end perspective with ActionCable.</p><h4>Back-end</h4><p>This is a little bit more complicated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*Uc_GdznX3eS0AYEHybhOsA.jpeg" /><figcaption>Anycable VS AtionCable architecture. Source: <a href="https://github.com/anycable/anycable-rails">anycable-rails repo</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wXuFDSv7dcxtJQQgAfP8TQ.png" /><figcaption>Closer look to AnyCables architecture. Source: <a href="https://evilmartians.com/chronicles/anycable-actioncable-on-steroids">ActionCable on steroids</a></figcaption></figure><p>First look just at big puctures gives as short list of changes: websocket server now lives by itself and ActionCable is replaced with AnyCable RPC based on <a href="https://grpc.io/">gRPC</a>.</p><h4>Minus Rack middleware</h4><p>This schema is already enough to make the first suggestion on what is already missing in AnyСable: despite a Rails application loading, AnyCable is an RPC service, and ActionCable is a Rack-based application. That means all Rack-middlewares are unavailable and don’t work out of the box with AnyCable! And if you need any of its functionality you should build workarounds manually.</p><p>The most valuable example of such critical middleware is the Warden middleware and devise gem which depends on it. Here is an example of <a href="https://stackoverflow.com/questions/38470463/rails-devise-action-cable">StackOverflow hint</a> on devise usage with ActionCable:</p><pre>def find_verified_user <br>  # this checks whether a user is authenticated with devise<br>  if verified_user = env[&#39;warden&#39;].user<br>    verified_user<br>  else<br>    reject_unauthorized_connection<br>  end<br>end</pre><p>In AnyCable it’s completly useless since there is no middleware and env[&#39;warden&#39;] always equals nil.</p><p>Here is an example on how you can emulate intended behaviour in AnyCable:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a42fcdfe6aa50bbaa28437e207f1f08e/href">https://medium.com/media/a42fcdfe6aa50bbaa28437e207f1f08e/href</a></iframe><h4>Connection and Channel methods: from active to passive</h4><p>One more change follows ws-server separation aside from Rails codebase and transforming Rack-base to gRPC: it’s migration from active to passive behaviour of some Connections/Channels methods. In ActionCable they actually did some action, for example making calls to redis and so. In AnyCable many of them just preparing RPC answer.</p><p>One more change follows ws-server separation aside from Rails codebase and transforming Rack-based to gRPC: it’s migration from active to passive behaviour of some Connections/Channels methods. In ActionCable they actually did some action, for example making calls to redis and so. In AnyCable many of them just preparing RPC answer.</p><p>Like, for example, a stop_all_streams method. In ActionCable it would go directly to redis, and in AnyCable it just raises some flag and until you return results to ws-server — nothing would happen.</p><p>How this knowledge may come handy? In two ways actually: when an exception raised after stop_all_streams call ActionCable streams would be stopped anyway, and in AnyCable they would not, and in case of some misbehaviour at a junction of AnyCable and ws-server is good to know were different things are actually done.</p><h4>Long live Connection!</h4><p>In an application based on ActionCable ActionCable::Connection instances live through all connection time, not only Channels object but Connection objects also.</p><blockquote>actioncable/lib/action_cable/channel/base.rb</blockquote><blockquote><em>Channel instances are long-lived. A channel object will be instantiated </em><strong><em>when </em></strong><em>the cable consumer becomes a subscriber, and then lives </em><strong><em>until </em></strong><em>the consumer disconnects.</em></blockquote><blockquote><em>Long-lived channels (</em><strong><em>and connections</em></strong><em>) also mean you’re responsible for ensuring that the data is fresh. If you hold a reference to a user record, but the name is changed </em><strong><em>while </em></strong><em>that reference is held, you may be sending stale data </em><strong><em>if </em></strong><em>you don’t take precautions to avoid it.</em></blockquote><p>Now we may notice the next difference in an AnyCable realization: there are no long-lived objects inside AnyCable! All objects get instantinated only at a time of RPC call through <a href="https://github.com/rails/globalid">globalid gem</a> serialization/deserialization process.</p><p>It means that all ActiveRecord objects relayed to connection through idetified_by call, now will be reloaded before use, i.e. current_user in AnyCable is equal to current_user.reload in ActionCable.</p><p>In one way it’s suitable because all objects now always in an actual state. But this has a slight drawback — now ActiveRecord objects used as Channel identifiers may additionally hit DB.</p><h4>Enjoy the silence…</h4><p>Lets review InternalChannel and RemoteConnections classes ( they both placed in ActionCable::Connection namespace ).</p><p>Every connection object not only controls a user channel subscription but also subscribed on an internal channel, which is used when there is a need to finish this connection.</p><p>Lets run usual demo-app, from an ActionCable guide, connect to it from two different browsers, subscribe on two different channels and take a look whats inside redis.pubsub:</p><pre>2.4.1 :020 &gt; redis.pubsub(&#39;channels&#39;)</pre><pre>=&gt; [&quot;action_cable/Z2lkOi8vYWN0aW9uY2FibGUtZXhhbXBsZXMvVXNlci8x&quot;, <br>&quot;messages:1:comments&quot;, <br>&quot;messages:2:comments&quot;, &quot;action_cable/Z2lkOi8vYWN0aW9uY2FibGUtZXhhbXBsZXMvVXNlci8z&quot;]</pre><p>Channels starts with a ‘messages’ prefix are chat rooms channels from the demo-app code, and channels with a ‘action_cable/’ prefix are the internal channels one per each connection, one for each browser ( not a tab ).</p><p>Now lets run AnyCable example and look inside Redis pubsub: there is only one message queue, by default its called __anycable__!</p><p>What can we derive from that? First of all, a total cables throughput is limited to a throughput of a one redis pubsub queue. Second is that many StackOverflow hints which were hits now are misses, for example: <a href="https://stackoverflow.com/questions/36106542/how-do-i-find-out-who-is-connected-to-actioncable">How do I find out who is connected to ActionCable?</a> or <a href="https://stackoverflow.com/questions/32905259/actioncable-how-to-display-number-of-connected-users">ActionCable — how to display number of connected users?</a></p><p>Back to the begining of this topic, lets look inside a RemoteConnections to review how things are done in a remote disconnecting:</p><pre>ActionCable.server<br>           .remote_connections<br>           .where(current_user: User.find(1))<br>           .disconnect</pre><p>and in a disconnect method:</p><pre>server.broadcast internal_channel, type: <strong>&quot;disconnect&quot;</strong></pre><p>So as you can see ActionCable sends a disconnect message through an internal channel. But AnyCable doesn’t have internal channels! It means that you surely can broadcast a disconnect message, but it will silently go nowhere.</p><p>As a compatibility table states:</p><blockquote>Disconnect remote clients : Nope</blockquote><p>Can we do this in AnyCable appllication?</p><p>Without changing ws-server, there is no reliable way to disconnect selected user from a Rails application code. You can do this through customized front-end Channel class, which may try to drop a connection after recieving a proper message. If JS ignore by some reasons your disconnect message, than you’ll have to wait till your favorite ws-server realization gets updated or at least restarted.</p><h4>Couple words about config</h4><p>How to configure ActionCable you can <a href="http://guides.rubyonrails.org/action_cable_overview.html#configuration">read in an official ActionCable guide</a>. Shortly: pubsub adapter configured in config/cable.yml, and the rest through config.action_cable inside application.rb or environment files.</p><p>You can read about an AnyCable configuration <a href="https://github.com/anycable/anycable-rails#configuration">in anycable-rails repo</a>.</p><p>Main difference:</p><ul><li>AnyCable doesn’t use cable.yml for any of its configuration, because AnyCable doesn’t use adapters as abstraction and also doesn’t alow different pubsub subscription source except for redis pubsub*.</li><li>AnyCable settings runned by <a href="https://github.com/palkan/anyway_config">anyway_config</a> gem, so they can be configured in different ways, through config/anycable.yml, or ENV, or even through Anycable.configure call.</li></ul><p>About settings syncronization between ws-server and RPC/rails code you can find in generated default config available in anycable-rails since version 0.5.2.</p><p>*This is valid for current version of anycable-rails ( 0.5.2 ), more<a href="https://github.com/anycable/anycable-rails#configuration"> pubsub sources are in discussions and plans</a>.</p><h4>Cross Site WebSocket Hijacking (CSWSH).</h4><p>Finally lets say a little about WebSocket security. If you are using secured sockets the only security threat, you left with is the Cross Site WebSocket Hijacking (CSWSH). It can be easily prevented by a proper origin check inside either your reverse proxy or your application.</p><p>When you are starting a ws-server supported by AnyCable you may introduce a set of headers wich would be delivered by ws-server to an application, like this:</p><pre>-headers=cookie,x-api-token,<strong>origin</strong></pre><p>As you can see, you can allow cookies for a session determination and an origin header for connection validation. But right now in anycable-rails 0.5.2 AnyCable RPC lost process method call nand default check <strong>allow_request_origin?</strong> inside of it:</p><pre><em># </em><strong><em>ActionCable</em></strong><em>::Connection::Base<br># Called by the server </em><strong><em>when </em></strong><em>a new WebSocket connection is established. This configures the callbacks intended for overwriting by the user.<br># This method should not be called directly -- instead rely upon on the #</em><strong>connect</strong><em> (and #</em><strong>disconnect</strong><em>) callbacks.</em></pre><pre><strong>def </strong>process <em>#</em><strong><em>:nodoc:<br>  </em></strong>logger.info started_request_message<br>  <strong>if </strong>websocket.possible? &amp;&amp; <strong>allow_request_origin?</strong><br>    respond_to_successful_request<br>  <strong>else<br>    </strong>respond_to_invalid_request<br>  <strong>end<br>end</strong></pre><p>You need to deliver origin validation by yourself in your application Connection class, using original ActionCable implementation of <strong>allow_request_origin? </strong>and a <a href="http://guides.rubyonrails.org/action_cable_overview.html#allowed-request-origins">proper config</a>:</p><pre>config.action_cable.allowed_request_origins = [&#39;<a href="http://rubyonrails.com&/#39;">http://rubyonrails.com&#39;</a>, %r{<a href="http://ruby.*/">http://ruby.*</a>}]</pre><p>Or you can move validation to your reverse proxy.</p><h4>Conclusion</h4><p>I liked AnyCable and its features, all the little differences I discover while incorporating it I’d rather consider as small distinctions not the flaws. But I would not recommend to use them both together but in different environment, ActionCable in development and AnyCable in production. I think it’s little bit complicated way to use only AnyCable, but it more robust.</p><p><em>Many thanks to </em><a href="https://github.com/palkan"><em>Vladimir Dementyev</em></a><em> (AnyCables author) for gem and comments to this article.</em></p><h3>Links</h3><h4>ActionCable:</h4><ol><li><a href="http://guides.rubyonrails.org/action_cable_overview.html">ActionCable guide</a></li><li><a href="https://stackoverflow.com/questions/36106542/how-do-i-find-out-who-is-connected-to-actioncable">How do I find out who is connected to ActionCable?</a></li><li><a href="https://stackoverflow.com/questions/32905259/actioncable-how-to-display-number-of-connected-users">ActionCable — how to display number of connected users?</a></li><li><a href="https://www.sitepoint.com/create-a-chat-app-with-rails-5-actioncable-and-devise/">Chat app rails 5 + ActionCable + devise</a></li><li><a href="https://github.com/rails/actioncable-examples/">ActionCable examples</a></li></ol><h4>Anycable:</h4><ol><li><a href="https://evilmartians.com/chronicles/anycable-actioncable-on-steroids">AnyCable — ActionCable on steroids</a></li><li><a href="http://anycable.io/">Anycable.io</a></li><li><a href="https://github.com/anycable">Anycable repo</a></li></ol><h4>WebSockets security:</h4><ol><li><a href="https://www.owasp.org/index.php/Testing_WebSockets_(OTG-CLIENT-010)">OWASP testing websockets</a></li><li><a href="https://www.theseus.fi/bitstream/handle/10024/113390/Harri+Kuosmanen+-+Masters+thesis+-+Security+Testing+of+WebSockets+-+Final.pdf?sequence=1">Security testing of WebSockets Final</a></li><li><a href="https://www.christian-schneider.net/CrossSiteWebSocketHijacking.html">Cross Site WebSocket Hijacking by Cristian Schneider</a></li><li>Security.stackexchange.com: <a href="https://security.stackexchange.com/questions/76816/preventing-csrf-attacks-against-websocket-communications">Preventing CSRF against Websockets</a>, <a href="https://security.stackexchange.com/questions/115716/is-the-origin-header-really-useful-for-securing-a-websocket">Is Origin header useful for websocket protection</a>.</li><li><a href="https://stackoverflow.com/questions/30144233/how-to-set-websocket-origin-header-from-javascript">How to set WebSocket Origin Header from Javascript?</a> ( it’s impossible, you can change the origin, but you may loose cookies, if you keep cookies — you can’t do nothing with origin)</li><li><a href="https://gist.github.com/subudeepak/9897212">The problems and some security implications of websockets — Cross-site WebSockets Scripting (XSWS)</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e8d863dd4cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>