The 2MB/3MB Bundle Budget: Performance Architecture That Scales

The 2MB/3MB Bundle Budget: Performance Architecture That Scales

Why bundle size matters at scale, how to implement a strict budget, measuring Core Web Vitals, and real optimization techniques that work in production.

The 2MB/3MB Bundle Budget: Performance Architecture That Scales

Bundle size matters. A lot. Not for trendy reasons—for actual user experience. Every 100KB added to your bundle is approximately 1 second slower for users on slow networks. On your portfolio and AI demo, the 2MB warning / 3MB error limit isn't arbitrary—it's a performance discipline.

Why Bundle Size Matters

The Math

| Bundle Size | 3G Network | 4G Network | Time Saved (per visit) |

|------------|-----------|-----------|----------------------|

| 1MB | 2.5s | 0.4s | Baseline |

| 2MB | 5s | 0.8s | +1.1s |

| 3MB | 7.5s | 1.2s | +2.2s |

| 5MB | 12.5s | 2s | +4.2s |

Real Impact

  • 2 seconds slower = 7% drop in conversion rates
  • 5 seconds slower = 40% bounce rate increase
  • This is especially critical for portfolios where first impression = potential clients

Measuring Your Bundle

bash# See actual bundle size
ng build --configuration production --analyze
# Opens visualization of what's taking space

# Get detailed breakdown
npm run build 2>&1 | grep "Initial chunk files" -A 5

The 2MB/3MB Budget Framework

| Size | Status | Action |

|------|--------|--------|

| < 2MB | ✅ Green | Ship confidently |

| 2-3MB | ⚠️ Warning | Review & optimize |

| > 3MB | 🔴 Error | Fail CI/CD, fix required |

This creates continuous pressure to optimize.

Common Bundle Killers (And Fixes)

1. Unused Dependencies (The Silent Killer)

bash# Find unused packages
npm list --production
# Check actual imports
npx depcheck

# Example: You import moment but use date-fns
# Result: +250KB unused
Fix:
bash# Remove unused packages
npm uninstall moment

# Use tree-shaking friendly alternatives
# ❌ moment (250KB)
# ✅ date-fns (13KB for what you use)
# ✅ dayjs (2KB)

2. Importing Too Much from Large Libraries

typescript// ❌ Bad: Imports entire lodash (70KB)
import _ from 'lodash';
const reversed = _.reverse(array);

// ✅ Good: Import only what you need (2KB)
import reverse from 'lodash/reverse';
const reversed = reverse(array);

// ✅ Better: Use native JavaScript
const reversed = [...array].reverse();

3. Angular Built-ins You're Not Using

typescript// Check what's in your bundle
ng build --stats-json

// Angular 20 common bloat:
// - Entire HttpClient (50KB) if you only use REST
// - Full Signals ecosystem (10KB) if only using Observables
// - All locales for i18n (200KB+) if only using English

// Solution: Selective imports
import { HttpClient } from '@angular/common/http';  // Only what you need
// Not: import * from '@angular/common';

4. Third-Party UI Libraries

typescript// Typical sizes
// Material: 200-400KB
// Bootstrap: 150-250KB
// Custom CSS: 5-20KB

// Example: You use Material for 3 components (button, input, select)
// But you get all 50 components

// Fix: Use design tokens instead
// @import '@angular/material/prebuilt-themes/indigo-pink.css';  ❌ 300KB
//
// Instead: Minimal CSS
// custom-theme.css (with SCSS variables): 2KB ✅

Advanced Optimization Strategies

1. Differential Loading

Angular automatically generates:

  • Modern bundles (ES2020) for Chrome/Safari: Smaller
  • Legacy bundles (ES5) for IE: Larger
json{
    "build": {
        "builder": "@angular-devkit/build-angular:browser",
        "options": {
            "aot": true,  // Ahead-of-time compilation (reduces size)
            "vendorChunk": false,
            "extractLicenses": false,
            "buildOptimizer": true  // Remove dev code
        }
    }
}

2. Lazy Loading Routes

typescript// ❌ All routes load upfront
const routes = [
    { path: '', component: HomeComponent },
    { path: 'blog', component: BlogComponent },
    { path: 'projects', component: ProjectsComponent }
];

// ✅ Load routes only when needed
const routes = [
    { path: '', component: HomeComponent },
    {
        path: 'blog',
        loadComponent: () => import('./blog/blog.component')
            .then(m => m.BlogComponent)
    },
    {
        path: 'projects',
        loadComponent: () => import('./projects/projects.component')
            .then(m => m.ProjectsComponent)
    }
];
Result: Initial bundle 200KB smaller, routes load in 100ms when needed.

3. Library Code Splitting

typescript// Heavy libraries loaded on demand
const generateDocument = () => {
    return import('pdfkit').then(({ default: PDFDocument }) => {
        // Now pdfkit is loaded, use it
        return new PDFDocument();
    });
};

4. Remove Polyfills for Modern Browsers

typescript// Angular 20 with modern browsers only
// Remove IE11 polyfills
// Saves 50-100KB

// package.json scripts
{
    "build:modern": "ng build --aot --buildOptimizer",
    "build:legacy": "ng build --aot --buildOptimizer --configuration es5"
}

Measuring What Matters: Core Web Vitals

typescript// Track actual performance
web.vitals.getCLS(metric => console.log('CLS:', metric.value));
web.vitals.getLCP(metric => console.log('LCP:', metric.value));
web.vitals.getFCP(metric => console.log('FCP:', metric.value));

// Real portfolio metrics (from Lighthouse)
// ✅ FCP: 552ms
// ✅ LCP: 679ms
// ✅ CLS: 0 (perfect)
// ✅ TTFB: 50ms

// These come from:
// 1. Small bundle (2MB total)
// 2. Lazy loaded routes (blog, projects load separately)
// 3. Optimized images
// 4. Minimal JavaScript execution on homepage

CI/CD Integration: Make It Fail

yaml# .github/workflows/build.yml
name: Build & Bundle Check
on: [push, pull_request]

jobs:
    build:
        runs-on: ubuntu-latest
        steps:
            - uses: actions/checkout@v3
            - uses: actions/setup-node@v3
              with:
                  node-version: '20'
            - run: npm install
            - run: npm run build
            - name: Check bundle size
              run: |
                  SIZE=$(stat -f%z dist/browser/main-*.js | awk '{s+=$1} END {print s}')
                  if [ $SIZE -gt 3145728 ]; then
                      echo "❌ Bundle > 3MB ($SIZE bytes)"
                      exit 1
                  elif [ $SIZE -gt 2097152 ]; then
                      echo "⚠️  Bundle > 2MB ($SIZE bytes)"
                  else
                      echo "✅ Bundle OK ($SIZE bytes)"
                  fi

Real Example: This Portfolio

Before Optimization

  • Total: 3.2MB (failing budget)
  • Angular core: 400KB
  • Material: 250KB
  • Unused dependencies: 180KB
  • Large images: 800KB

Optimization Process

  1. Removed Material UI → Custom CSS (saves 250KB)
  2. Removed unused RxJS operators → Tree-shaking (saves 80KB)
  3. Lazy load blog & projects (saves 400KB from initial)
  4. Optimize images with Next.js Image component (saves 300KB)
  5. Remove moment.js dependency (saves 180KB)

After Optimization

  • Total: 1.9MB (passing budget)
  • Core bundle: 450KB
  • Custom styles: 15KB
  • Optimized images: 500KB
Result:
  • Initial load: 2.3s → 0.8s (65% faster)
  • Lighthouse score: 85 → 98
  • Bounce rate: 12% → 3%

Best Practices Checklist

  • ✅ Bundle budget in CI/CD (fail on > 3MB)
  • ✅ Tree-shake enabled in production build
  • ✅ Lazy loading for non-critical routes
  • ✅ Minification & gzip enabled
  • ✅ Unused dependencies removed quarterly
  • ✅ No import * from large packages
  • ✅ Images optimized & resized
  • ✅ Third-party scripts loaded async
  • ✅ CDN for static assets
  • ✅ Monitor bundle trends month-over-month

The Philosophy

Bundle size is a proxy for performance discipline. If you can keep it under 2MB, you've made good decisions about:
  • What dependencies matter
  • What code ships by default
  • What loads on demand
  • What's truly necessary

Make the budget aggressive. Optimize early. Your users (and conversion rate) will thank you.


Need to trim your bundle? Let's audit your code and identify the biggest optimization opportunities.