Optimizing Mastodon Performance: Finding and Fixing its N+1 Queries
Tags: mastodon, rails, ruby, vscode
Published: 2023-01-12 18:34:06

[N+1 queries](https://appmap.io/blog/2021/02/04/eager-loading-and-the-n-plus-one-query-problem/) happen in a variety of ways, out of sight to many developers who are using an [ORM](https://en.wikipedia.org/wiki/List_of_object%E2%80%93relational_mapping_software). With the level of abstraction that ORMs provide, it can be easy for developers to accidentally incorporate a query that is executed on each result of the previous query. ORMs can make development faster and more secure, but the automatic generation of SQL queries can make it hard to predict the code's performance when it gets deployed.

Developers can be unaware their functions even query the database and a simple feature like checking user permissions could lead to querying for the same exact data multiple times. 

[Active Record](https://guides.rubyonrails.org/active_record_basics.html) is a Ruby on Rails framework used to easily save and retrieve objects from a database in programming frameworks. It automatically generates SQL statements to do this. ORMs like Active Record can make it easier for developers to write database-backed applications, but they can also make it harder to understand exactly how their code makes database queries.

In this final part of our Mastodon Series, you’ll learn how to [analyze your AppMaps](https://appmap.io/docs/analysis) to uncover and fix an N+1 SQL query in an active code base. 

In the previous posts you have learned:
- [How you can install AppMap into Mastodon](https://dev.to/appmap/installing-appmap-in-mastodon-with-vs-code-167d)
- [How to visualize Mastodon code internals](https://dev.to/appmap/visualizing-mastodon-internals-1198)
- [How to run the Mastodon rspec tests](https://dev.to/appmap/the-fastest-way-to-run-mastodon-tests-5g03). 
- [How to automatically generate OpenAPI docs for Mastodon](https://dev.to/appmap/automatically-generating-openapi-docs-for-mastodon-42ig)

In our previous post, you learned how AppMap uses the runtime code data to automatically generate accurate OpenAPI documentation. AppMap contains all the relevant HTTP request information including status codes, headers, and the session operations and AppMap builds complete and accurate OpenAPI documentation by analyzing how the code executes.

This same AppMap data can be used in other ways, for example in this post you’ll learn how to use AppMap Analysis to locate and fix a performance issue. Since the AppMaps shows function calls, SQL queries, exceptions, and more, they can be analyzed to find design flaws that contributes to performance and security issues. 

Design related security flaws are rising in the [OWASP Top 10](https://owasp.org/www-project-top-ten/) in recent years. Runtime data helps us to uncover design flaws that are contributing to slow performance such as an N+1 query. 

![1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pho87ucrn6897ts6xk0w.png)

## Generate Code Analysis Findings
With our `rspec` tests passing and our AppMaps created back in [Part 3](https://dev.to/appmap/the-fastest-way-to-run-mastodon-tests-5g03), findings are now shown in the section of our VSCode extension titled “Runtime Analysis”. Since AppMap records the runtime application behavior, it analyzes the output of those recordings and scans for code behavior issues that you can’t find with a static analyzer. 

AppMap can scan for a variety of [Performance, Security, Scalability, and Maintainability issues](https://appmap.io/docs/analysis/rules-reference). These [rules are extensible](https://github.com/getappmap/appmap-js/tree/main/packages/scanner/src/rules) for developers to create and contribute to the open source community. 

On the left side of the VS Code extension, you can see a section called “Runtime Analysis”. This is where AppMap will display the results of the analysis scan. This scan should happen within seconds of AppMaps being created or updated. 

![2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9ycz4aanscaix01crbor.png)

When clicking on any one of the lines of code referenced in the findings, a new tab will open with additional details about the event, including links to the relevant [CWE](https://cwe.mitre.org/). The findings page will also show the stack trace leading up to the event, and a list of the AppMaps this flaw is present in.

![3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b5atrszgu8cr6gm67uv9.png)

By navigating to the base controller in Mastodon, AppMap identifies this line of code (Line 92) as making a database call (via User.find) when the `doorkeeper_token` variable is false. But by looking closer at the stack trace, AppMap shows line 109 is the caller function which checks to see if the current user is known and properly validated. This is correctly reported by AppMap as an N+1 query.

https://github.com/mastodon/mastodon/blob/623d3d2e32ac8ec2819f2cd99e6565d06c9b0023/app/controllers/api/base_controller.rb#L111-L141

![4](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/evc5usl7o27ppsc0lil4.png)

A simple fix would be to just fetch current_user once in require_user!, or to memoize it in the current_user function. 

AppMap [visualizes this function and the repeated SQL queries](https://app.land/scenarios/a8878519-7709-45e7-883b-38d56d90ce77?process=true&state=eyJjdXJyZW50VmlldyI6InZpZXdGbG93Iiwic2VsZWN0ZWRPYmplY3QiOiJldmVudDoxMTUxIiwidHJhY2VGaWx0ZXIiOiJpZDoxMTY1IGlkOjEyMDUgaWQ6MTI0NyBpZDoxMjg3IGlkOjEzMzMgaWQ6MTM3MyBpZDoxNDEzIGlkOjExNTEgIn0
).

![5](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6tltclbmguf777zrfeus.gif)

## Understanding the Before and After
Before implementing the code change, save the original AppMap in a “Baseline” collection so that AppMap can visually compare the before and after impact of the change. 

This code is found in 6 AppMaps and they are listed on the specific findings page. 

![6](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4dqrm7xxnvw0dnhubkjv.png)

Now select one of these AppMaps, right click them, and choose the option to “Save To Collection”. Collections can be used to create copies of AppMaps which is useful for saving the current code behavior as a baseline before you implement code changes. 

![7](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aacqbdqqotcfb3r0orh4.png)

From there we can click `<create>` to create a new collection of AppMaps or select a previously created collection to add to. 

![8](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y0hwsbjk8l1k5731e408.png)

After copying that AppMap to a new collection, you’ll see it included within the list of existing AppMaps. 

![9](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/az6wz6cyr00emm5douom.png)

It’s important to note that this makes a copy of the AppMap in the state it was in when it was added to the Collection. After updating the code and the AppMap, the collection will still contain the previous version of the code. 
## Implementing the Performance Fix

This poorly performing code is improved by [breaking out the user validation into its own function](https://github.com/mastodon/mastodon/pull/23057/commits/b677187280abb6d66c165098f9d8faac067fe6bc) so it will not repeatedly query the database for the same information. 

https://github.com/mastodon/mastodon/pull/23057

![10](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v1skcyeu8ndo5zlypdbv.png)

## Identify Out of Date AppMaps
After making this code change (either committed to your project or not) AppMap will display both the baseline and other maps that are listed as out of date because we’ve changed the functions these maps had previously recorded. AppMap knows when the underlying code has been changed and can notify when the AppMaps no longer match the code. 

![11](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uouojccdnn35psv7le2g.png)

Open the Command Palette in VS Code (View -> Command Palette OR Shift+⌘+P on Mac OR Ctrl+Shift+P on Windows), and search for the option to “Copy Out-of-Date Tests”.

![12](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9exoa6rceto9p30mvfl0.png)

![13](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/upgbnz9rmoet2pkuhk99.png)

You can choose to copy the file names into the clipboard and paste them into the `rspec` command. 

![14](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rwx3iydrraop1r5fhkoo.png)

After successfully running only the tests needed to update our AppMaps the baseline AppMap will continue to be out of date and the other AppMaps will be updated. It’s important to note that when you make a code change to a function recorded in the “Baseline” AppMap, that AppMap will always display as “out of date” since it will always represent the original test case run. 

![15](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z9dpn9veqsm3adpybgft.png)

## Generating Sequence Diagram Diffs
Another feature of AppMap is the ability to [automatically create sequence diagrams](https://dev.to/appmap/auto-magically-generate-sequence-diagrams-of-your-codes-runtime-behavior-597a) of your code’s runtime behavior. This can be extremely useful information to include in a pull request or a code review to help other members of your team understand how the code behavior has changed.  

Since a baseline AppMap exists prior to our code change, AppMap can create a sequence diagram diff of the before and after. Assuming the local VS Code environment is [configured to support sequence diagram creation](https://appmap.io/docs/diagrams/sequence-diagrams.html), AppMap will be able to both generate a sequence diagram, or compare two sequence diagrams. 

![16](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g0pubawb1jywd2c17cod.png)

To generate the sequence diagram diff, right click on the latest version of the AppMap and select “Compare Sequence Diagrams”

Hit enter twice then select the original baseline AppMap saved in our Baseline collection. 

![17](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0tgo2kvqpi7h404766dj.png)

From here a new browser window will open showing a sequence diagram diff visualizing the change in behavior of the code from before and after our changes. The red items in sequence diagram will indicate code behavior that has been removed, and green items will show new code paths created. 

![18](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m12htyetc1njet0ej069.png)

Now the changes in the sequence diagram show the code is not longer making similar repeated SQL queries. By reducing these unnecessary queries the speed of this code function has increased. 
## Summary
In this post, you’ve learned how to find and fix a performance issue in the Mastodon code base using AppMap. The automated code analysis will work for other projects written in languages other than Ruby like Java, Python, and JavaScript/TypeScript. 

To get started finding potential issues in your code base, download and install the [AppMap VS Code Extension](https://marketplace.visualstudio.com/items?itemName=appland.appmap), or the [JetBrains Marketplace](https://plugins.jetbrains.com/plugin/16701-appmap/reviews) in your code editor and follow the similar instructions taken in this project. For more language specific information, check out the [AppMap documentation](https://appmap.io/docs/install-appmap-agent.html), or join the [AppMap Community Slack](https://appmap.io/slack) to ask a developer for more information.