Sub topic 14
Keeping the gains: budgets and CI checks
Earlier chapters showed how to shrink the app and speed up its first frame. This chapter covers keeping those results. Size and startup time get worse a little at a time, one dependency, asset or await per pull request. A budget plus an automated check turns "we should watch this" into a failing build.
This chapter assumes you can run flutter build apk --analyze-size, read build/start_up_info.json from --trace-startup, and write a short shell or Dart script. It also assumes you have used a CI service such as GitHub Actions.
Why regressions slip through
Nobody decides to add 3 MB. A package pulls in a transitive dependency, a designer exports a PNG at 4x, or someone adds a plugin initialization to main(). Each change looks harmless in review because the diff doesn't show the size or the delay.
Three conditions make regressions stick:
- Nobody measures after each change, so the cost goes unnoticed.
- The measurement is unreliable, so people ignore it.
- A failing check has no owner or process, so it gets disabled.
A good budget system handles all three: it measures automatically, uses stable numbers, and states what to do when a limit is hit.
Choose what to track
Track a small set of numbers. Each one should map to something a user feels.
| Metric | Source | Why it matters |
|---|---|---|
| Release APK size for one ABI | Size of `app-release.apk` after a release build | Approximates download size on the most common device type |
| Per-category size breakdown | `--analyze-size` JSON file | Shows which category grew (Dart code, assets, native libraries) |
| Time to first frame | `timeToFirstFrameMicros` in `build/start_up_info.json` | The delay between launch and the first rendered Flutter frame |
| Time to framework init | `timeToFrameworkInitMicros` in the same file | Separates engine startup from your own `main()` work |
Pick one reference configuration and never change it silently. For example: release mode, android-arm64, one named device. Comparing a number from an arm64 build with one from a different configuration tells you nothing.
Measure size in CI
A size check has two jobs. It fails the build when a budget is exceeded, and it saves the analysis file so a reviewer can see what changed.
The script below builds one ABI with --analyze-size, reads the APK size and compares it with a budget.
#!/usr/bin/env bash
set -euo pipefail
# Budget for the arm64 release APK, in bytes (12 MiB here).
BUDGET_BYTES=$((12 * 1024 * 1024))
APK=build/app/outputs/flutter-apk/app-release.apk
flutter build apk --analyze-size --target-platform android-arm64
ACTUAL_BYTES=$(wc -c < "$APK" | tr -d ' ')
echo "APK size: ${ACTUAL_BYTES} bytes (budget: ${BUDGET_BYTES})"
if [ "$ACTUAL_BYTES" -gt "$BUDGET_BYTES" ]; then
echo "FAIL: APK is over budget by $((ACTUAL_BYTES - BUDGET_BYTES)) bytes" >&2
exit 1
fi
echo "OK: within budget"--analyze-size also prints a breakdown and the path of a *-code-size-analysis_*.json file. Keep that file as a CI artifact for every build. To investigate a failure, open the DevTools app size tool, load the analysis file from the failing build, and use the diff view to compare it with a file from the last passing build.
Measure startup in CI
Startup is harder to measure than size, because it depends on the device, its temperature, what else is running and whether the app was recently launched. flutter run --profile --trace-startup needs a real device or emulator attached, and it writes build/start_up_info.json.
The file holds values in microseconds. Key names such as timeToFirstFrameMicros and timeToFrameworkInitMicros can differ between Flutter versions, so open one file from your version before writing any parser.
The Dart script below reads one such file and compares the first-frame time with a budget in milliseconds.
import 'dart:convert';
import 'dart:io';
const budgetMs = 1500;
void main(List<String> args) {
final path = args.isNotEmpty ? args.first : 'build/start_up_info.json';
final json = jsonDecode(File(path).readAsStringSync()) as Map<String, dynamic>;
final micros = json['timeToFirstFrameMicros'];
if (micros is! int) {
stderr.writeln('timeToFirstFrameMicros missing or not an int in $path');
exit(2);
}
final ms = micros / 1000;
stdout.writeln('Time to first frame: ${ms.toStringAsFixed(1)} ms '
'(budget: $budgetMs ms)');
if (ms > budgetMs) {
stderr.writeln('FAIL: startup over budget');
exit(1);
}
}A single run is too noisy to gate on. Run the measurement several times on the same device and compare the median with the budget:
for i in 1 2 3 4 5; do
flutter run --profile --trace-startup --no-resident
cp build/start_up_info.json "build/startup_$i.json"
doneExtend the Dart script to read all five files, sort the values and use the middle one. The median ignores one slow outlier, such as a run where the OS was busy indexing.
Set a budget that people respect
A budget is a limit with some slack. Use this process:
- Measure the current value several times on your reference configuration.
- Set the budget a little above it. A margin of 3 to 5 percent for size is common. For startup, set the margin from the spread you saw between runs.
- Write the budget in a file under version control, not inside a CI dashboard. Changing it then requires a pull request.
- Tighten it after a successful reduction. If you cut 1 MB and leave the budget alone, the next change can silently spend that gain.
When a check fails, there are two valid outcomes. The author reduces the cost, or the author raises the budget in the same pull request and explains why in the description. Both leave a record. Raising a budget should be possible, but visible.
Put the checks in a pipeline
The diagram shows a typical flow. The size job needs no device, so it can run on every pull request. The startup job needs a device, so it often runs less often, for example on merges to the main branch or nightly.
Here is a GitHub Actions job for the size check. It uses the subosito/flutter-action setup step.
name: size-budget
on:
pull_request:
jobs:
apk-size:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: subosito/flutter-action@v2
with:
channel: stable
cache: true
- run: flutter pub get
- run: bash tool/check_size.sh
- uses: actions/upload-artifact@v4
if: always()
with:
name: code-size-analysis
path: ~/.flutter-devtools/*code-size-analysis*.jsonThe if: always() line matters. You want the analysis file most when the check has failed. The path above is where the Flutter tool saves the file on many setups, but confirm it from the path printed in your own build log.
For startup, run the job on a self-hosted runner with a physical device attached, or on a device farm. Emulators are fine for catching large regressions, but their timing varies more between runs.
Common errors
- Comparing different configurations. A debug build compared with a release build, or arm64 compared with a universal APK. Fix the reference configuration in the script, not in people's heads.
- Gating on one startup run. Noise causes false failures, and people then learn to ignore the check. Use the median of several runs.
- Budgets stored only in the CI UI. Nobody reviews changes to them. Keep them in the repository.
- Dropping the artifact on failure. Without the analysis file, the author has to rebuild locally to find the cause.
- Never tightening. A budget that sits 20 percent above the current size permits large regressions.
- Ignoring toolchain upgrades. A new Flutter or Dart version can change both size and startup. Treat an upgrade pull request as a change that may need a new baseline, and record the old and new numbers in it.
Review the trend, not only the gate
A pass/fail gate catches large jumps but not slow growth inside the margin. Append the measured size and median startup time, with the commit hash, to a file or dashboard on every merge to main. A monthly look at that series shows drift the gate allows. When the trend rises, use the diff view in DevTools between an old and a new analysis file to find the category that grew, then return to the earlier chapters on assets, dependencies and deferred loading to fix it.
Exercise
Your size check passes locally but fails in CI by 400 KB, and the code did not change. Give two likely causes and one step to find out which applies.
Show answer
Likely causes are a different Flutter or Dart version in CI than on your machine, and a different build configuration (for example a different target platform or a dependency resolved to a newer version because pubspec.lock is not committed). To find out, compare the output of flutter --version in both places and the target platform flags, then load the analysis files from both builds into the DevTools app size tool and use the diff view to see which category differs.
Exercise
Why does the startup check use the median of five runs on one reference device, and why is the budget stored in the repository?
Show answer
A single run is noisy, so the median of several runs avoids failing on one slow outlier, and a single reference device keeps the numbers comparable. Storing the budget in the repository means any change to it goes through a pull request, so a raised limit is visible and explained instead of being quietly edited in a CI dashboard.