DEV Community

Hirohisa Tanaka
Hirohisa Tanaka

Posted on

My Own CLI Made Me Wait Five Minutes

My own CLI took five minutes to complete its first sync. The first thing I did was check the logs.

The takeaway

The first sync of ghusage, a CLI that aggregates GitHub activity, took 295 seconds for 30 days of data. I reduced API calls, fetched pages in parallel, and revisited SQLite and CI.

Sync Before → after
First sync, 30 days 295 seconds · 2,015 requests → 124 seconds · 952 requests
Incremental sync, 30 days v0.1.4 average: 14.8 seconds → v0.1.5 average: 6.2 seconds, with roughly the same number of requests

Here's the source code: https://github.com/tanahiro2010/ghusage

Getting from 295 seconds to 124 seconds wasn't the end of the story. After reducing API calls, I still had page-fetching delays during incremental syncs. After fixing SQLite, column-name lookups were still showing up in aggregation time, and that aggregation test was blocking CI.

This article is about speeding up ghusage, a project I'll be talking about at OSC Osaka 2027. I'm also documenting measurement conditions that didn't make it into the slides, as well as approaches I didn't adopt. It's for people building CLIs in Rust who are figuring out how to find the slow parts. The numbers were transcribed from my work notes; they haven't been reproduced in an independent environment.


1. Waiting five minutes for the first sync

ghusage is a CLI that syncs GitHub activity such as commits, Pull Requests, reviews, comments, and CI, then aggregates it by time period. Synced data is stored in a local SQLite database.

The first sync of 30 days of data from a real account took 295 seconds on an M4. It made 2,015 API requests. Five minutes is a long time to ask a first-time user to wait.

During sync, ghusage searches GitHub for PRs and commits, fills in details such as Issue information and CI status, then saves everything to the local database. The total time of 295 seconds alone doesn't tell us whether there were too many network requests, whether dependent stages were waiting on one another sequentially, or whether aggregation after saving was slow.

I started by looking at the total runtime, the number of requests, and the start and end times of each request. Just saying “it's slow” doesn't tell you whether there are too many API calls, whether requests are being made sequentially, or whether local processing is the bottleneck. So I ran a sync in JSON format and compared api.requests with the GitHub client's debug logs.

I used this command locally:

GHUSAGE_LOG=ghusage_github=debug ghusage sync --format json
Enter fullscreen mode Exit fullscreen mode

I used api.requests in the JSON output to count total requests, then tracked each request's elapsed_ms in the debug logs. Later, when investigating incremental sync, I also worked backward from the end time and start time to arrange requests chronologically. First, I looked at the total count, then at the breakdown.

Following the logs showed that ghusage was fetching details for Issues that hadn't changed since the previous sync. If the previous fetch was complete and the search result's updated_at was unchanged, there was no need to fetch the details again. If the previous fetch was incomplete, I didn't skip it, and I didn't advance the sync cursor. The next sync could try again.

CI results for Pull Request head commits were also being fetched through the REST API, one PR at a time. According to my implementation notes, that meant three requests per PR: the PR itself, check runs, and commit statuses. I changed the GraphQL query that fetches PRs to include CI results, falling back to REST only when statuses are present.

I didn't eliminate every REST call. If the GraphQL response doesn't include the required statuses, the existing REST fetch remains in place, preserving a way to retrieve missing information.

With these changes to skip unnecessary fetches and parallelize sync stages, the first sync went from 295 seconds to 124 seconds, and the request count went from 2,015 to 952. This is a before-and-after comparison that combines multiple changes. I can't attribute the difference between 295 and 124 seconds to a single fix.

I considered changes that reduce the number of requests separately from changes that increase concurrency. In one test using the same 30-day period, I compared concurrency levels of 4 and 8: the request count stayed at 952, while the time dropped from 180 seconds to 124 seconds, and the aggregate results matched. This helped keep the effect of halving the request count separate from the effect of overlapping network waits.

I changed the default number of concurrent requests from 4 to 8. The limit remains 16. I made 8 the default only after confirming that the overview numbers still matched after changing the concurrency level. Parallelism changes the order in which work happens, so I also compared the results.

I also made a change to skip syncs altogether in some cases. If less than five minutes have passed since the previous sync, a second weekly or daily run doesn't sync again; it generates a report using data up to the last sync time. This doesn't make sync itself faster. It's a way to eliminate the wait for people who open reports repeatedly within a short time.

By limiting the report period to the last sync time, the report doesn't make it look as though data is available for a period that hasn't been fetched yet. If you always want the latest data, you can disable this behavior with --max-age 0.

I also changed what users see while waiting. Nothing appeared during sync, so it looked as if the process had stalled. In a terminal, progress now overwrites two lines. It doesn't display anything for operations that finish within 300ms, and it doesn't clutter piped output. After adding parallelism, I also made it show the number and names of HTTP requests currently in progress. The wait may be just as long, but now it's clear what the CLI is waiting for.

This display doesn't flood the terminal with logs. It updates the same two lines and clears them when sync finishes. It doesn't appear when piping JSON output. First, I made it possible to see whether the CLI was searching and how many items had been processed; then I added the requests running concurrently.

2. The seven-second commit search was waiting on pages

After the first sync, the next thing I looked at was incremental sync, which is used more often. Even after reducing unnecessary API calls, syncing 30 days of data still took about 15 seconds. I arranged each request's start and end times from the debug logs and found that the nine pages of commit search were fetched one at a time, consuming about seven seconds sequentially.

Here's what the timeline looked like:

0.5–2.2s   /search/issues ×3
2.2–3.5s   /graphql (PR)
3.3–10.5s  /search/commits ×9  ← serialized here
10.5–11.9s /repos/*/commits        (parallel)
11.7–14.1s /repositories/<id>/commits ×6 (serialized)
Enter fullscreen mode Exit fullscreen mode

Some requests overlapped with PR search; other requests waited for the response to page 1 before requesting page 2. The total runtime doesn't show the difference. The serialized parts only became visible once I laid out the request start and end times.

To build this timeline, I worked backward from the log's elapsed_ms and end time to calculate the start time. Looking only at the order of log output can make concurrent requests and sequential waits look like one another.

The first page of a Search API response includes total_count. Since search results are fetched 100 at a time, up to a maximum of 1,000 results, I can fetch pages 2 and onward concurrently. For REST pagination, when the response's Link header identifies the last page, I also fetch the pages in between in parallel. Rather than constructing page URLs from scratch, I update only the page number in links that have passed host validation. If the results grow and the last page has a link to the next page, I follow that too.

Commit search also didn't need to wait for PR search to finish. The list of PR repositories is only needed later, when fetching commits from default branches. So I started commit search first and waited for the PR results only at the point where the repository list was needed.

In other words, I didn't start every task all at once. I ran commit search and PR search in parallel because they don't depend on each other, then waited for the PR results only when fetching commits from default branches.

I compared v0.1.4 and v0.1.5, published on npm, by alternating runs against the same real account and the same 30-day period. I ran each version two or three times, leaving 90 seconds between runs.

Published version Incremental sync API requests
v0.1.4 14.8 seconds average 45–47
v0.1.5 6.2 seconds average 46–47

That's about a 2.4× speedup, but the number of measurements is small. At least in this comparison, the main difference wasn't fewer requests; it was overlapping time that had previously been spent waiting sequentially.

The first sync didn't improve in the same way. v0.1.4 took 97.9 seconds and ended in partial status; v0.1.5 took 109.9 seconds and completed. Both were delayed by Search API rate limits, and my notes say that the first sync wouldn't improve unless the number of search requests was reduced.

In other words, overlapping page waits during incremental sync didn't address the bottleneck in the first sync. When authenticated search hits its request limit and has to wait, parallelizing pages doesn't help if the same number of searches is still required.

Parallelism also had a side effect. GitHub's Search API started returning incomplete_results: true more often. My notes show incomplete results in 0 of 3 runs before parallelization and about 2 of 5 afterward. Speed doesn't help if sync completes with missing search results.

Incomplete pages are retried with exponential backoff, up to two times. If the results are still incomplete, I leave Coverage marked as partial and don't advance the sync cursor for that range. All four syncs spaced apart over time completed successfully, and one of them retried a page. I look at whether the results are complete, not just at the speed numbers.

If the sync cursor advanced while search results were missing, the next sync wouldn't go back to fetch that range. That's why the database needs to retain a partial status even after the retry limit has been reached.

I kept changed-line counts out of regular sync

I also wanted the number of lines added and deleted in commits. Fetching each commit individually through the REST API would mean 1,000 requests for 1,000 commits. So I designed it as a separate operation, run only when needed:

ghusage sync --diff-stats
Enter fullscreen mode Exit fullscreen mode

Line counts for commits included in a PR can already be included in the GraphQL query that fetches the PR. The rest are fetched in batches of 100. The generated query uses aliases for repositories and commits:

query CommitLineCounts {
  r0: repository(owner: "octo", name: "app") {
    c0: object(oid: "<full-commit-sha>") {
      ... on Commit { additions deletions }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

In the implementation, <full-commit-sha> is replaced with a 40-character SHA. The owner, repository name, and SHA are validated before being interpolated into a GraphQL string. For seven days of data from a real account, 472 of 1,153 commits were fetched along with the PR query, with zero additional requests. The remaining 681 commits were fetched in batches as needed; one record shows about 12 requests for 1,147 commits. On the second run, ghusage uses the line counts it has already fetched, so it doesn't fetch them again.

A commit's diff only needs to be fetched once

In the TUI, you can open a commit diff from a Pull Request. Previously, every time you opened it, ghusage fetched the commit details from GitHub, with pagination if the commit had many files. The commit message, parent commit, file list, and diff are now saved in SQLite's commit_details. From the second time onward, they can be opened from the cache, so the display works even without a network connection. The initial fetch runs on a separate thread, so it doesn't block TUI key input while loading.

3. Column-name lookups remained after fixing the JOIN

While revisiting API sync, I noticed that cargo test took six to eight minutes in CI, depending on the OS. Before increasing workflow parallelism, I broke down the logs and found that in benchmark test mode, reading seven days of data from the cache took 131–173 seconds, and reading 30 days took 169–240 seconds.

These figures are measurements from a Debug build using 100,000 events. They are not the normal runtime of the release build we distribute. But this was definitely blocking CI tests, and the same processing also runs when users aggregate a large cache.

The query that collects events for each PR originally looked like this:

SELECT {EVENT_COLS} FROM activity_events e
JOIN account_events ae ON ae.event_id = e.event_id
WHERE ae.account_id = ?1 AND e.parent_pr_id = ?2
Enter fullscreen mode Exit fullscreen mode

There were indexes. The problem was which table SQLite started reading from. Without statistics, it scanned account_events first and then looked for that account's events for each PR.

-- JOIN as before
SEARCH ae USING PRIMARY KEY (account_id=?)
SEARCH e USING INDEX ... (event_id=?)
Enter fullscreen mode Exit fullscreen mode

Reading 100,000 events once wouldn't take this long. The query scanned all the account's events once per PR, multiplying the work by the number of PRs. Changing the join to CROSS JOIN fixed SQLite's join order and changed the plan to fetch events using the parent_pr_id index.

SELECT {EVENT_COLS} FROM activity_events e
CROSS JOIN account_events ae ON ae.event_id = e.event_id
WHERE e.parent_pr_id = ?2 AND ae.account_id = ?1
Enter fullscreen mode Exit fullscreen mode
-- CROSS JOIN
SEARCH e USING INDEX activity_events_parent_pr (parent_pr_id=?)
SEARCH ae USING COVERING INDEX account_events_event (event_id=? AND account_id=?)
Enter fullscreen mode Exit fullscreen mode

I wrote more about this join-order issue, EXPLAIN QUERY PLAN, and the measurements in a separate article. What I want to focus on here is what remained after the Debug benchmark dropped to one to three seconds.

Seven days of data took one to two seconds, and 30 days took three seconds. According to my notes, the total CI time also dropped from about 13 minutes to about 8 minutes.

Looking at the execution plan showed that, without statistics, SQLite read all of an account's events first and repeated that process for each PR. Reading 100,000 events once isn't a huge load, but the number of PRs multiplied the work.

The release aggregation for seven days had a p95 of 654ms on a CI runner, down from 226ms. It was still above my 200ms target at the time. Rather than changing SQL at random, I ran the benchmark continuously on macOS and took a sample profile.

Near the top were rusqlite::RowIndex::idx, columnName, and string comparison functions. For each event row, the code was looking up about 20 columns by name. I changed it to look up the column positions once per query, then read each row by position.

The updated read path creates the column positions once at prepare time and passes them to the row conversion:

let mut stmt = conn.prepare(sql)?;
let cols = EventCols::of(&stmt)?;
let mut rows = stmt.query(params)?;

while let Some(row) = rows.next()? {
    out.push(cols.event(row)?);
}
Enter fullscreen mode Exit fullscreen mode

Inside EventCols::of, the code calls things like stmt.column_index("event_type") and records the column number for event_type. Each row uses the number instead of the name.

let ty: String = r.get(self.event_type)?;
Enter fullscreen mode Exit fullscreen mode

Looking up a column by name seems like a small operation, but with about 20 columns per row, repeated for every event in the time period, it accounted for a significant portion of the aggregation profile.

In measurements on the same CI runner, the seven-day p95 dropped from 226ms to 145ms, and the 30-day p95 was 223ms. I also confirmed that nine types of aggregate results and three PR details were byte-for-byte identical before and after the change. On an M4, after five warmup runs, I measured 50 runs: 93.8ms for seven days and 126.2ms for 30 days. You shouldn't mix numbers from different environments into a single before-and-after comparison.

Events from before the requested period were needed only to calculate things like the time to the first review on PRs I created. For other people's PRs, events within the period were enough, so I narrowed the historical reads to my own PRs and confirmed that nine outputs, including overview and reviews, were byte-for-byte identical to the previous version.

One note: the seven-day p95 is recorded as both 643ms and 654ms in different places. The improved result is 145ms in both, but I haven't resolved the discrepancy in the previous value. I report 643ms in the comparison table and keep it separate from the 654ms in another benchmark record.

4. I looked at the tests before parallelizing Actions

At first, I wondered, “Would parallelizing Actions make it faster?” But if a single aggregation in a test takes more than two minutes, fixing the product's processing first is more effective. The SQLite JOIN fix alone reduced CI from about 13 minutes to about 8 minutes as a side effect.

After that, I continued splitting up CI work. Separating tests and the release build into different jobs brought the total time from about 8.3 minutes to 6.7 minutes. Consolidating heavy, platform-independent checks on Ubuntu and using rust-lld on Windows brought it down to about five minutes. After measuring again with a warm cache, Windows tests went from 4.2 minutes to 2.8 minutes, and macOS Intel tests went from 6.5 minutes to 3.1 minutes. The first run took 12.1 minutes because the cache key had changed and dependencies had to be rebuilt. It was important to also measure with a warm cache. Finally, I skipped the release build on dev pushes, bringing the recorded time down to three minutes.

I didn't remove tests from every OS. I moved only OS-independent formatting and performance tests to Ubuntu, while keeping clippy and regular tests on each OS, including tests for code that branches by OS. I replaced the MSVC linker, which links Windows test binaries, with rust-lld, included with Rust.

Those three minutes are for a dev push. Release PRs don't take the same amount of time. The release build remains part of release validation.

I also built a mechanism to skip the work in a job when rerunning a successful CI with the same input files. It hashes the combination of input files and skips the job if it has already been verified. Re-running with the same content went from 11.6 minutes to about 25 seconds. This isn't the runtime of an initial CI run; it's a case where the same inputs are reused.

Each job lists the input files it needs, and the contents of those files are used to create a cache key. A successful job leaves a record that the inputs have been verified for that OS. The next run checks for the same key and skips the work if it finds one. The job itself still needs to return success as a required check, so I skip only the work inside the job rather than removing the job.

If the input list is empty, the job fails. Calculating a hash from an empty list could incorrectly mark inputs as “verified” even though no changes had ever been checked. The core of the workflow is just a little shell script:

files=$(git ls-files -s -- "$@")
test -n "$files" || { echo "no inputs matched: $*" >&2; exit 1; }
printf '%s\n' "$files" | sha256sum | cut -c1-40
Enter fullscreen mode Exit fullscreen mode

I also cancel an older run when a new one arrives for the same branch or PR, so that multiple pushes don't let outdated CI run to completion. It doesn't cancel checks for unrelated commits; it cancels outdated checks for the same target.

I also fixed some flaky tests to reduce CI reruns. For a timeout test, what I wanted to verify was the number of client retries. Strictly asserting how many requests reached the server can fail on a slow runner if the deadline expires before the last attempt arrives. I changed the test to verify the client's retry count and increased the deadline from 300ms to one second. The upper bound I'm checking remains the same.

Previously, the test assumed a response would arrive within 300ms. On Windows runners, the same test sometimes saw four attempts reach the server and sometimes nine, so it was measuring how slow the environment was rather than the retry logic I wanted to test.

The release build no longer runs on every dev push. It still runs for release-bound PRs and on the release branch; dev pushes continue to run tests and clippy. The workflow condition looks like this:

build:
  if: >-
    (github.event_name == 'pull_request' && github.base_ref == 'release')
    || github.ref == 'refs/heads/release'
Enter fullscreen mode Exit fullscreen mode

After adding this condition, a dev push took about three minutes. I didn't get it down to three minutes by removing release validation.

5. Things I tried and reverted

There were changes I tried but didn't adopt.

I increased SQLite's page cache to 32MiB because file reads stood out in the profile. However, my machine was under heavy load, and the measurements varied by a factor of two to six, so I couldn't determine whether it helped. I reverted the setting. I didn't want to claim a speedup based on a lucky number without first stabilizing the measurement environment.

pread and memory copies also remained near the top of the profile, but the CLI loads the aggregate data only once per run. I reasoned that a larger page cache would help only in cases like repeatedly reloading the TUI, so I didn't make it a permanent setting without being able to verify the benefit.

I also investigated build times with cargo build --timings. On my machine, a clean build took 44 seconds in dev and 62 seconds in release. The biggest component was the aws-lc-sys build script. In an experiment switching the TLS library from AWS-LC to ring, the clean release build dropped from 62 seconds to 56 seconds, but the dev build remained at 44 seconds. I didn't think the improvement justified changing the cryptography library, so I didn't adopt it. This was about build time, not runtime performance.

In release builds, libsqlite3-sys took another 21 seconds to build, and the final link, including LTO, took 16 seconds. In development builds, incremental builds took about eight seconds, so the biggest component of a clean build isn't necessarily the best target for improving the everyday edit loop.

The incremental test build already took about eight seconds. Changing the debug information settings resulted in times between 7.8 and 10.8 seconds, so I couldn't call that an improvement. The build breakdown also showed that AWS-LC was building concurrently and wasn't the bottleneck for the overall development build.

The benchmarks also fluctuated. I once saw an aggregation process that hadn't changed appear about 10% slower in a comparison between the baseline and PR versions. Possible causes include the order in which the baseline was measured first, but I haven't confirmed the cause. One approach I'm considering is alternating between measurements of the baseline and PR versions.

To avoid relying on whatever load my local machine happens to have, I also created a workflow for release-bound PRs that measures the baseline and PR on the same GitHub Actions runner and comments with the Criterion median, p95, and percentage change. For the v0.1.2 PR, the baseline aggregation was so slow that it hit the 60-minute limit. For v0.1.3, the recorded seven-day p95 went from 654ms to 145ms, and the 30-day p95 went from 806ms to 223ms. Even on the same machine, measuring in a fixed order doesn't eliminate bias.

6. The first sync is still waiting on search

The first sync made too many API requests. For incremental sync, the bottleneck was serial page-fetching delays rather than the total number of requests. After the API, the problems were SQLite's query plan and row reads. Fixing those also shortened CI runtime.

What I looked at changed each time I investigated a problem. For API sync, I looked at api.requests and request timestamps; for SQLite, I looked at EXPLAIN QUERY PLAN and sample profiles; for CI, I looked at job start and end times. It wasn't possible to make every decision based on a single number.

Incremental sync is faster now. But the Search API rate limit still causes delays during the first sync. v0.1.4 took 97.9 seconds and ended in partial status; v0.1.5 took 109.9 seconds and completed. Parallelizing search pages alone won't make this faster. My next step is to reduce the number of Search API calls during the first sync.

References

Top comments (0)