<?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 Will Koffel on Medium]]></title>
        <description><![CDATA[Stories by Will Koffel on Medium]]></description>
        <link>https://medium.com/@wkoffel?source=rss-2263be4cbb12------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*cLsio6fDnKuMB0qK.jpeg</url>
            <title>Stories by Will Koffel on Medium</title>
            <link>https://medium.com/@wkoffel?source=rss-2263be4cbb12------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 18:45:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wkoffel/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[MySQL, Rails and Metadata Locks: a Bug Hunt Bedtime Story]]></title>
            <link>https://medium.com/@wkoffel/mysql-rails-and-metadata-locks-a-bug-hunt-bedtime-story-c9c4e14deb36?source=rss-2263be4cbb12------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9c4e14deb36</guid>
            <category><![CDATA[locks]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[mysql]]></category>
            <dc:creator><![CDATA[Will Koffel]]></dc:creator>
            <pubDate>Wed, 21 Sep 2016 17:44:33 GMT</pubDate>
            <atom:updated>2016-09-21T17:44:33.868Z</atom:updated>
            <content:encoded><![CDATA[<p>C’mon, c’mon! Brush your teeth, grab your blanky and crawl in. Tonight, we’re going tell a story of hunting giant bugs. In <em>production</em>! With one hand tied behind our backs. And I promise you, it’s all <em>true…..</em></p><h3>TL;DR</h3><p>A long-running report job was taking down our whole site. But not in any of the naïve ways one might expect. We learned:</p><ul><li>Long-running SELECT statements block ALTER TABLE queries due to MySQL metadata locks. All SELECTS behind the ALTER TABLE also get blocked</li><li>Rails ActiveRecord doesn’t close connections from the connection pool when you think it does</li><li>acts-as-taggable-on improperly advises that users force binary collation in tables inside an initializer, which runs for each resque workers spawned</li><li>MySQL 5.6 doesn’t clearly report metadata locks</li></ul><h3>The Story</h3><p>As with all great bug hunting stories, this one is distinctly non-linear. But for fear of you dozing off before we get to the punchline, let me spin the yarn in a more streamlined fashion.</p><p>It starts with a pretty typical Ruby on Rails setup:</p><ul><li>Rails 4.2 on EC2 in an auto-scaling group</li><li><a href="https://github.com/macournoyer/thin">thin</a> instances handling web traffic</li><li>MySQL 5.6 database hosted on RDS</li><li><a href="https://github.com/resque/resque">Resque</a> and cron-like sidekick <a href="https://github.com/resque/resque-scheduler">resque-scheduler</a> handling background jobs</li></ul><h4>Symptoms</h4><p>Like many sites, we have an administrative backend, and one of it’s features is generating some reports. Some of these can take as much as 15 minutes to generate depending on the parameters, so of course we run them in a background job resque worker.</p><pre>def self.get_records report_type: nil, **options<br>    query = build_query(**options)</pre><pre>    ActiveRecord::Base.connection.exec_query(query.to_sql)<br>    <br>    {<br>      columns: build_record({}).keys,<br>      rows: results.collect { |row| self.build_record(row).values }<br>    }<br>end</pre><p>The query takes about 2 minutes, and iterating through the build_record calls takes about 10 minutes, depending on the size of the report (generally on the order of 100K rows)</p><p>We were seeing a problem, however, where these long running report jobs would sometimes have the effect of <strong>taking down the whole site</strong>. Ruh-roh…</p><p>The site wouldn’t just get slow, it would stop responding entirely. At which point, the EC2 ELB and auto-scaling group would turn into puppies in a pillow factory and start wreaking havoc in a futile effort to “help”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*f1OfBfRA5hMy0q8zYagcig.jpeg" /></figure><p>Now we had upset customers who were getting 503s, <em>and</em> upset internal stakeholders who were being told not to push the report button.</p><h4>Aside: Debugging in Production</h4><p>As it turns out, our report jobs didn’t take down environments other than production. Of course. Because as long as the bug is confusing, let’s make it appear only in production, #amiright?</p><p>Now to be fair, we don’t currently have a production-like environment with the same full set of data and simulated live user traffic. To the two readers who do have that and thus think you are better than the rest of us: yeah, yeah…buzz off.</p><p>So unfortunately, this meant that we had to do all our debugging at off hours on the live site. It really upped the ante on designing each test knowing it was likely to take users offline for a few minutes. Such is life in a startup!</p><h4>Forensics</h4><p>Given that a background job was taking down the main web tier of our application, and that it seemed related to a long-running report query, it was clear pretty early on that the culprit was MySQL contention.</p><p>We first looked at CloudWatch for any clues. CPU, memory, connections, network traffic all looked within reasonable bounds.</p><p>We considered whether there was network I/O contention at the database caused by a large amount of data streaming back from our report query, but optimizations there yielded no difference.</p><p>We also examined more closely the downtime, which lasted approximately 15 minutes. We observed that the downtime started just as the big query was finishing, and then didn’t clear up until after the whole report job was done, not just the short 2 minute DB query part of it.</p><p>So what’s left, you ask?? <strong>Locks, child. Locks.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mj2D0J0q8ISPNCVYFtz2xA.jpeg" /></figure><h4>Metadata Locks</h4><p>As we all know, the InnoDB engine is famous for “row locking” instead of “table locking”. And further, we all know that this locking happens while waiting for writes and during transactions that include writes. Write^H^H^H^H^HRight? <strong>Wrong!</strong></p><p>Well, sort of wrong. It turns out, there’s also <a href="https://dev.mysql.com/doc/refman/5.6/en/metadata-locking.html">metadata locks</a>, which lock a table when its schema or settings are being modified.</p><p>So here’s the summary the <strong>gotcha</strong>, kids:</p><pre>SELECT * from widgets;</pre><pre>ALTER TABLE widgets ....; &lt;--- This will wait for the SELECT</pre><p>This seems obvious, of course. If MySQL were willing to change the table schema during SELECT statements, or during multiple-SELECT transactions, all hell would break loose.</p><p>Unfortunately, MySQL 5.6 does a <a href="https://www.pythian.com/blog/deal-metadata-lock/">terrible job</a> of revealing that there are metadata locks outstanding, which resulted in our debugging heroes enduring a wild goose chase looking for locks.</p><p>Eventually, we noticed a clue in SHOW ENGINE INNODB STATUS output, in the form of a query that was waiting on a metadata lock:</p><pre>---TRANSACTION 0, not started<br>mysql tables in use 1, locked 1<br>MySQL thread id 2067430, OS thread handle 0x2ae7d4aa8700, query id 4708605990 170.31.60.131 newco Waiting for table metadata lock<br>ALTER TABLE tags MODIFY name varchar(255) CHARACTER SET utf8 COLLATE utf8_bin</pre><p>Whoa, whoa, whoa, stop the clock. <strong>Why</strong> would an alter table be happening right now? We are debugging intensive report jobs, not doing a deployment with database migration!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/0*r0Ht6ns99SrR7ixy.gif" /></figure><h4>Europeans and Tags</h4><p>So we’re nearly finished, but before the big finale, our story needs the requisite flashback.</p><p>Once upon a time, we had a customer from Europe. Like many Europeans, this customer uses a character set that the infinite wisdom of the ASCII designers could never have predicted. So this customer, unwilling to take <strong>Ñø</strong> for an answer, inspired us to make sure accented characters worked in our tags.</p><p>We use the venerable <a href="https://github.com/mbleigh/acts-as-taggable-on">acts-as-taggable-on</a> gem, which per popular <a href="https://github.com/mbleigh/acts-as-taggable-on/issues/623">issue 623</a>, indicates that in order to properly handle special characters, one should set the collation on the tags table in MySQL to utf8_bin. Fair enough, we said.</p><p>We followed the instructions on the acts-as-taggable-gem README, and modified our initializer as such:</p><pre>config/initializers/acts_as_taggable_on.rb:</pre><pre>ActsAsTaggableOn.force_binary_collation = true</pre><p>And once again, Euro-American relations were comfortably back at defcon 4.</p><h3>Puzzle Picture Revealed</h3><p>So my young detective, have you pieced the whole puzzle together yet? You now have all the clues….</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*v8VmxelpqYZcNQbQjaefvA.jpeg" /></figure><p>I see you clutching your blanky with anticipation, so let’s walk the mystery together so you can get some sleep. Here’s what the situation looks like:</p><ol><li>User pushes the button to generate an admin report</li><li>A resque worker starts up, running a 2-minute long SELECT query</li><li>That query creates a metadata lock on the “tags” table</li><li>That query completes, but does not get autocommitted until the database connection is returned to the pool, which doesn’t happen when exec_query() finishes, but rather when….well, <a href="https://tenderlovemaking.com/2011/10/20/connection-management-in-activerecord.html">it’s complicated</a>.</li><li>Meanwhile, on the other side of Gotham city, we have a resque-scheduler job which is firing off once per minute on a seemingly unrelated task</li><li>Each of those minutely jobs launches a Rails thread, invokes the initializers, thus calling ActsAsTaggableOn.force_binary_collation, which, <strong>you guessed it</strong>, calls an ALTER TABLE!!</li><li>Now MySQL diligently tells that ALTER TABLE statement to wait until the SELECT transaction is complete.</li><li>On a site where there is live traffic (of course, not on our test site), users are now clicking around the site, and need to retrieve tags. But MySQL forces all their SELECTs on the tags table to wait for the ALTER TABLE, which is in turn waiting on the original long-running SELECT</li><li>Once we get enough of these waiting requests (depends on site load), we have no further thin processes to to handle incoming requests</li><li>The site goes down hard. ELB/ASG ➡ puppies and pillows.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*i7KP2JDm_D2Hst29yIxBjw.png" /></figure><h4>Assigning a Root Cause</h4><p>As to what “caused” this bug, it was close to a perfect storm of things coming together. Most of them individually make sense, but caused emergent behaviors in our system. Despite the deep ingrained desire of engineers to place blame, this one isn’t so cut and dry.</p><p>There are two misdemeanor offenses here, both related:</p><ol><li>ActsAsTaggableOn should never have suggested that you put a function into an initializer which causes a schema change to the database. This schema change should be done once in a migration, and never needs to be done again.</li><li>We shouldn’t have paid attention to that piece of bad advice. And various team members had seen this ALTER TABLE statement in logs, but just let it slide. It’s a good reminder than when something smells, it’s best to clean it up before the smell turns into a stink for your customers!</li></ol><p><strong>Solution: </strong>We removed the ALTER TABLE call. And for good measure, we also explicitly close the connection in our long-running report jobs after we’ve completed the DB queries, so we clear the metadata locks when we know we’re not going to be issuing any more statements on that connection.</p><p>Here’s response time when running reports before and after the deploy. Sleep well, little one. Sleep well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*CGZ4Vl_3aJ8eS0mbO1Gfxg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9c4e14deb36" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shortcomings of GitHub Oauth for Multiple Scope Permission Levels]]></title>
            <link>https://medium.com/@wkoffel/shortcomings-of-github-oauth-for-multiple-scope-permission-levels-d4e959d2c6fe?source=rss-2263be4cbb12------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4e959d2c6fe</guid>
            <category><![CDATA[oauth]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[outlearn]]></category>
            <dc:creator><![CDATA[Will Koffel]]></dc:creator>
            <pubDate>Thu, 29 Oct 2015 20:01:38 GMT</pubDate>
            <atom:updated>2016-09-02T17:38:49.654Z</atom:updated>
            <content:encoded><![CDATA[<p>Outlearn is in the business of building a superior learning platform for professional developers, so we obviously adore GitHub. It’s both an inspiration for us, and a valuable technical integration.</p><p><em>However…</em></p><p>This is a story about how GitHub OAuth falls frustratingly short of the mark for what seems like our simple use-case, most insidiously for the purpose of allowing users to escalate scope permissions when they want to give us additional access. We’d love to hear from other developers who’ve tackled these issues, and from the GitHub team.</p><p><strong>Edit</strong>: Jult 2016, GitHub sent me an update on progress they’ve made in these areas. See the bottom of this post for the latest.</p><h4>The Plan</h4><p>Our integration has two main goals:</p><ol><li>Allow developers a no-hassle way to register for an Outlearn account using their GitHub credentials.</li><li>For developers who want to publish on Outlearn, allow content in their public or private GitHub repos to be imported (usually via webhook) as Outlearn learning modules.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*GvzAkQkQvaO26ny7oRVN8Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*YEQWJNFs05XbRcfgYuiUPA.png" /></figure><h4>The Challenge</h4><p><em>A brief primer on </em><a href="https://developer.github.com/v3/oauth/"><em>GitHub Oauth</em></a>: Quickly becoming the defacto cross-application authorization protocol, OAuth describes the cartwheel you go through when one app (Outlearn) wants to access your data or API privileges on another app (GitHub). Outlearn redirects your browser to a specific GitHub URL that encodes the permissions (<em>scopes</em>) we’d like. You enter your password with GitHub (we never see it), and GitHub sends us back an authentication token which we can use for subsequent requests on your behalf. That token is only granted the permissions that you allow, never has more GitHub access than you yourself have, and can be revoked by you anytime you like. Overall a slightly convoluted, but very flexible system.</p><p>So the naive solution would simply be to ask for all the permissions we need at sign in. The <a href="https://developer.github.com/v3/oauth/#scopes">necessary scopes</a> that meet our goals are: <em>user</em> and <em>repo</em>.</p><p><strong>Note</strong>: GitHub does not allow read-only access to private profile information, nor to repositories. And as we’ll see in more detail below, acccess to all your repositories also typically grants access to the repos for all your organizations. So in practice, we need to ask users for read/write access to all their user and repository data, including full access to view and modify their source code. <em>Eek</em>!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*m9L783GN1IjrZgfa8mH-cA.png" /></figure><p>Here’s our problem. Just asking for these permissions outright falls short for two important reasons:</p><ul><li>Many users aren’t going to need to publish via GitHub (Outlearn has a cool visual path-assembly tool that suffices for many use-cases). They are understandably freaked out when we ask for such escalated permissions just to join a site with which they haven’t yet built a loving, loyal, trust-filled relationship. And damn right…you don’t give your apartment keys to the the cutie you just met in line at the pharmacy. At least not before you share some witty repartee, and Pseudoephedrine.</li><li>We <em>don’t want </em>all those permissions. All your base <em>should not </em>belong to us. It’s bad security practice to ask for more than you need. A junior developer experiences a rush of power the first time he’s given root access on a production machine. A seasoned developer grows a foreboding sense of dread with every additional machine she now has the power to fix, or destroy.</li></ul><p>So we went on a hunt for a better solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*5yAQ433yIOt3lof5ISSV0g.png" /></figure><h4>The Journey</h4><p>We had three ideas for improvements. And in fact, what we <em>really</em> want is all three of them together. So here they are.</p><p><strong>Idea 1:</strong> Request permissions only on the repositories we need</p><p>While GitHub has made some movement towards more <a href="https://developer.github.com/changes/2013-10-04-oauth-changes-coming/">granular user-controlled scopes</a>, there is no current way for a user to opt-out of certain repositories from the OAuth dialog, or later in their application settings.</p><p>Compounding the challenge here are organization-owned repositories. GitHub not only allows users to pass on their same level of access to any organization repos, they also <em>don’t not</em> allow it! <strong>For example:</strong> If you belong to GitHub organization “ClearlyTech”, and you OAuth to Outlearn, I’m also granting permissions to ClearlyTech content.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*8RmBFfKYhQmie32ShT_n2Q.png" /></figure><p>GitHub added “<a href="https://help.github.com/articles/about-third-party-application-restrictions/">3rd party app restrictions</a>” help address this, allowing an organization administrator to white-list certain applications that it trusts. (A user can “grant” or “request” access for an app into the whitelist). This is a good step, but this was not turned on by default until early 2015, and the vast majority of legacy organization owners do not appear to have enabled it. In addition, it puts extra friction into the OAuth workflow for users who would otherwise “do the right thing” and turn off org access in the OAuth screen without bothering their admin, if only they could.</p><p><strong>Idea 2:</strong> Only request read-permissions</p><p>The GitHub scopes do not allow us to request read-only access, either to profile data or to repositories. This seems strange, as almost all of the GitHub integrations we’ve seen would do quite well with read-only access. But the OAuth gods have spoken, and there we have it.</p><p><strong>Idea 3:</strong> Escalate permissions when a developer is ready to start publishing GitHub content to Outlearn.</p><p>This one is a little more complicated, but by far the most interesting. We tried creating three levels of OAuth access for our users:</p><ol><li>Not linked with GitHub.</li><li>Linked with GitHub, and authorized email and profile info (i.e. the <em>user</em> scope), so they can register and sign-in.</li><li>Linked with GitHub, and authorized both user and repository access (i.e. the <em>user</em> and <em>repo</em> scopes)</li></ol><p>We learned a few things when we tried this, and learned that it fell short of the elegant panacea we imagined.</p><p>It turns out that escalating scopes works quite nicely. When a user links with GitHub, we request level 2scopes. Later, when they are ready to get in deeper, we request the level 3 scopes, and the GitHub pop-up does a nice job showing the diff between them, so you can feel confident authorizing the upgraded permissions.</p><p>But now, imagine that you are logged out, perhaps on a different device. You come to Outlearn and click “sign-in with GitHub”. What scopes do we request??</p><p>What we want is a way to say to GitHub: “give me at least these permissions”, so we can request level 2 scopes, and if the user has already authorized level 3 scopes, GitHub just leaves us at level 3. But that’s not what happens. Instead, GitHub tries to downgrade the permissions back to level 2, which is confusing, and would break webhook integrations we already have in place, and force the user to upgrade their permissions regularly. Yucky.</p><p>One other note: Our site <strong>can</strong> say “give me whatever you had last time” (this is done by requesting empty scopes), but in the case where the user is registering for the first time, that breaks goal #1, because the empty scopes don’t give us enough information to seamlessly register you, and you get stuck with additional screens for your name and your (by default private-on-GitHub) email address.</p><h4>The Surrender</h4><p>So where does that leave us?</p><p>For now, we are staying where we started. We just ask for all the permissions, and put a little note telling people why they might want to grant them. And we allow them to sign-up without GitHub, which is extra work, but means they can link with full scopes only when it becomes necessary.</p><p>We are considering a few other options, like this doozy:</p><ol><li>Have a three-way github permissions toggle, [off] [level1] [level2], so users can escalate permissions when they are ready.</li><li>Ask for empty scopes when a user signs-in (and hope they didn’t mean join, in which case they’d get an extra step to prompt for private email address)</li><li>Ask for level 1 scopes on join (and hope they weren’t already a user with level 2 scopes, in which case we’d remove permissions and break their webhooks).</li></ol><p>We will be watching metrics for real users and listening to feedback from our developer audience, but have taken an approach for now that favors simplicity, and keeps the convenience vs. privacy decision in the hands of our Outlearn members.</p><p>What we ideally want is for GitHub to implement all three ideas above: granular repository permissions, read-only access, and the ability to request minimum scopes without implicitly removing permissions.</p><p><strong>Other developers</strong>: how have you tackled similar challenges for multiple levels of GitHub scopes in your apps? <a href="/service/mailto:snuggles@outlearn.com">Email us</a></p><p><strong>GitHub</strong>: we’d love to chat about how to improve this situation. You’ve clearly put a lot of work into granular permissions, it’d be a shame to not finish the job and handle some of these obvious gotchas. <a href="/service/mailto:snuggles@outlearn.com">Email us</a></p><h4>July 2016 Update: GitHub responds</h4><p>Github support wrote a great note back to me. Sounds like they are making good progress towards more flexibility of the oauth implementation. The relevant parts of the email are included here.</p><blockquote>I just wanted to followup and let you know that the team made some changes which should make this easier to implement.</blockquote><blockquote>First, it’s now possible to have multiple tokens for a specific user/application/scopes combination, as documented here:</blockquote><blockquote><a href="https://developer.github.com/v3/oauth/#multiple-tokens">https://developer.github.com/v3/oauth/#multiple-tokens</a></blockquote><blockquote>Second, when you send users through the OAuth flow without the scopes parameter listed, the token you get back will have all the scopes that the user granted you (not the scopes that they granted you the last time the went through the OAuth flow, which was the case before), as documented here:</blockquote><blockquote><a href="https://developer.github.com/v3/oauth/#parameters">https://developer.github.com/v3/oauth/#parameters</a></blockquote><blockquote>This means that you could implement multi-level permissions in your application like this:</blockquote><blockquote>1. the sign-in button on your site always send users through the OAuth flow with the basic set of scopes specified in the query parameters (e.g. user:email scope). When users go through that flow, your application gets a token with that set of scopes, regardless of whether the user already authorized your application or not.</blockquote><blockquote>2. in the settings of the application, you can allow users to grant your application the advanced permissions (e.g. repo scope). You’d provide a link to go through the OAuth flow again and specify those other scopes in the query parameter, and then get a new token with those scopes. This means that for users that grant you both basic permissions and advanced permissions — you’d have two separate tokens, one with the basic scopes and the other with the advanced scopes.</blockquote><blockquote>3. when such a user signs in again using the sign-in button, you’d get a new token with the basic scopes again, but you’d also have the token with advanced scopes from before (that token is still around). So, you can check which user signed into your application and then check for other tokens you have for them and see if they granted you one with more scopes. This means that you’d need to make changes on your end which allow you to store multiple tokens for a single user and track which token has which scopes.</blockquote><p>Thanks GitHub!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4e959d2c6fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>