The Power Of Query Comments

July 27, 2014

When people use frameworks they often rely on ORMs to generate queries for them. However when they are not explicitly writing the queries themselves it can be difficult to track their source when they show up in MySQL logs.

A pattern I find really useful is adding query comments that contain the source of the query.

For example:

SELECT * FROM users /*application:webapp,category:chill,route:users#get,all*/;

This allows us to quickly find the action that generated the query. At GitHub we use the Marginalia Gem to inject these comments. Marginalia also allows you to inject your own components.

A useful comment component to add is request id. This means you can match requests to slow queries in the logs for debugging.

Discussion, links, and tweets

If you like what I have to say you can Follow me on Twitter