trusty-mpm 1.3.4

trusty-mpm: unified multi-agent orchestration platform (core, daemon, CLI, TUI, Telegram)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
# Performance Optimization Techniques

Comprehensive guide to web performance optimization techniques across backend, frontend, and infrastructure.

---

## Table of Contents

1. [Backend Optimization]#backend-optimization - CRITICAL FOR TTFB
2. [Image Optimization]#image-optimization
3. [JavaScript Optimization]#javascript-optimization
4. [CSS Optimization]#css-optimization
5. [Resource Loading Optimization]#resource-loading-optimization
6. [Caching Strategies]#caching-strategies

---

## Backend Optimization

**Critical for:** TTFB (Time to First Byte) optimization

**Target:** TTFB <800ms (Good), <1800ms (Acceptable)

### Diagnostic Workflow

#### Step 1: Measure TTFB Components

Use curl to break down TTFB into phases:

```bash
# Create curl timing format file
cat > curl-format.txt << 'EOF'
time_namelookup:    %{time_namelookup}s\n
time_connect:       %{time_connect}s\n
time_appconnect:    %{time_appconnect}s\n
time_pretransfer:   %{time_pretransfer}s\n
time_starttransfer: %{time_starttransfer}s (TTFB)\n
time_total:         %{time_total}s\n
EOF

# Measure TTFB
curl -w "@curl-format.txt" -o /dev/null -s https://yoursite.com
```

**Interpretation:**
- `time_namelookup` >100ms: DNS is slow → Switch DNS provider or use CDN
- `time_connect - time_namelookup` >100ms: TCP connection is slow → Enable Keep-Alive
- `time_appconnect - time_connect` >200ms: TLS handshake is slow → Enable TLS 1.3
- `time_starttransfer - time_pretransfer` >500ms: **Server processing is slow** ← Most common

#### Step 2: Profile Backend (If Server Processing is Slow)

**Use Application Performance Monitoring (APM) tools:**
- New Relic
- Datadog
- Sentry Performance
- AWS X-Ray (for AWS services)
- Google Cloud Profiler

**What to look for:**
- Slow database queries (>100ms)
- N+1 query problems
- Missing database indexes
- Cache miss ratios
- External API call latency
- Cold start penalties (serverless)

#### Step 3: Optimize Bottleneck

---

### Database Query Optimization

#### Problem 1: N+1 Query Problem

**Symptom:** Making 1 query to fetch parent records, then N queries to fetch related data

**Python (Django ORM) Example:**

```python
# ❌ BAD: N+1 query problem
posts = Post.objects.all()  # 1 query
for post in posts:
    print(post.author.name)  # N queries (one per post)
    print(post.category.name)  # Another N queries

# Query count: 1 + N + N = 1 + 2N queries for N posts
# For 100 posts: 201 queries! (Execution time: ~2000ms)

# ✅ GOOD: Use select_related() for foreign keys
posts = Post.objects.select_related('author', 'category').all()  # 1 query with JOIN
for post in posts:
    print(post.author.name)  # No additional query
    print(post.category.name)  # No additional query

# Query count: 1 query for 100 posts (Execution time: ~50ms)
# Performance improvement: 40x faster

# ✅ ALSO GOOD: Use prefetch_related() for many-to-many
posts = Post.objects.prefetch_related('tags').all()  # 2 queries total
for post in posts:
    print([tag.name for tag in post.tags.all()])  # No additional queries
```

**Node.js (Sequelize) Example:**

```javascript
// ❌ BAD: N+1 query problem
const posts = await Post.findAll();
for (const post of posts) {
  const author = await post.getAuthor();  // N queries
  console.log(author.name);
}

// ✅ GOOD: Use include to eager load
const posts = await Post.findAll({
  include: [{
    model: Author,
    attributes: ['name']
  }]
});
for (const post of posts) {
  console.log(post.Author.name);  // No additional query
}
```

**Ruby (Rails) Example:**

```ruby
# ❌ BAD: N+1 query problem
posts = Post.all
posts.each do |post|
  puts post.author.name  # N queries
end

# ✅ GOOD: Use includes to eager load
posts = Post.includes(:author)
posts.each do |post|
  puts post.author.name  # No additional query
end
```

**Impact:** 10-100x faster (depends on number of records)

---

#### Problem 2: Missing Database Indexes

**Symptom:** Slow queries doing full table scans instead of index lookups

**Identify missing indexes:**

```sql
-- PostgreSQL: Find slow queries
SELECT query, mean_exec_time, calls
FROM pg_stat_statements
WHERE mean_exec_time > 100  -- Queries slower than 100ms
ORDER BY mean_exec_time DESC
LIMIT 10;

-- MySQL: Enable slow query log
SET GLOBAL slow_query_log = 'ON';
SET GLOBAL long_query_time = 0.1;  -- Log queries >100ms
```

**Analyze query execution plan:**

```sql
-- PostgreSQL
EXPLAIN ANALYZE
SELECT * FROM orders
WHERE user_id = 123 AND created_at > '2025-01-01';

-- Output shows "Seq Scan" (full table scan) = BAD
-- Want to see "Index Scan" = GOOD
```

**Add appropriate indexes:**

```sql
-- ❌ BAD: No index, full table scan
-- Query time: 2300ms for 1M rows

-- ✅ GOOD: Composite index for common query pattern
CREATE INDEX idx_orders_user_created
ON orders(user_id, created_at);

-- Query time: 15ms (153x faster!)

-- For filtering and sorting
CREATE INDEX idx_orders_status_created
ON orders(status, created_at DESC);

-- For covering index (all needed columns in index)
CREATE INDEX idx_orders_covering
ON orders(user_id, status)
INCLUDE (created_at, total);  -- PostgreSQL 11+
```

**Index best practices:**

1. **Index columns used in WHERE clauses:**
   ```sql
   -- Query: WHERE user_id = ? AND status = ?
   CREATE INDEX idx_user_status ON orders(user_id, status);
   ```

2. **Index foreign keys:**
   ```sql
   -- Always index foreign key columns
   CREATE INDEX idx_orders_user_id ON orders(user_id);
   ```

3. **Composite index order matters:**
   ```sql
   -- Query: WHERE user_id = ? AND created_at > ?
   -- CORRECT: user_id first (equality), then created_at (range)
   CREATE INDEX idx_user_created ON orders(user_id, created_at);

   -- WRONG: created_at first makes user_id filter less efficient
   CREATE INDEX idx_created_user ON orders(created_at, user_id);
   ```

4. **Don't over-index:**
   - Each index slows down INSERT/UPDATE/DELETE
   - Maximum 5-7 indexes per table
   - Monitor index usage and remove unused indexes

**Impact:** 10-1000x faster (depends on table size)

---

#### Problem 3: Fetching Too Much Data

**Symptom:** Fetching all columns when only a few are needed

```python
# ❌ BAD: Fetching all columns (including large text/blob fields)
users = User.objects.all()
# Fetches: id, email, name, bio (TEXT), avatar (BLOB), created_at, etc.
# Query size: 50KB for 100 users

for user in users:
    print(f"{user.name}: {user.email}")

# ✅ GOOD: Only fetch needed columns
users = User.objects.only('id', 'name', 'email')
# Query size: 5KB for 100 users (10x smaller)
# Query time: 70% faster

for user in users:
    print(f"{user.name}: {user.email}")

# ✅ ALSO GOOD: Use values() for even better performance
users = User.objects.values('id', 'name', 'email')
# Returns list of dicts instead of model instances
# Query time: 80% faster than fetching all columns
```

**SQL optimization:**

```sql
-- ❌ BAD: SELECT * fetches unnecessary data
SELECT * FROM users WHERE status = 'active';

-- ✅ GOOD: Only select needed columns
SELECT id, name, email FROM users WHERE status = 'active';
```

**Impact:** 50-80% faster for queries with large text/blob columns

---

#### Problem 4: Slow Aggregations

**Symptom:** Aggregating large datasets without optimization

```sql
-- ❌ BAD: Aggregating without index
SELECT user_id, COUNT(*) as order_count
FROM orders
WHERE created_at > '2025-01-01'
GROUP BY user_id;
-- Query time: 3000ms for 1M rows

-- ✅ GOOD: Add index on aggregation columns
CREATE INDEX idx_orders_created_user
ON orders(created_at, user_id);
-- Query time: 150ms (20x faster)

-- ✅ BETTER: Precompute aggregations (materialized view)
CREATE MATERIALIZED VIEW user_order_stats AS
SELECT
  user_id,
  COUNT(*) as order_count,
  SUM(total) as total_spent,
  MAX(created_at) as last_order_date
FROM orders
GROUP BY user_id;

-- Refresh periodically (e.g., hourly)
REFRESH MATERIALIZED VIEW user_order_stats;

-- Query the materialized view (1-2ms)
SELECT * FROM user_order_stats WHERE user_id = 123;
```

**Impact:** 20-100x faster for complex aggregations

---

### Server-Side Caching (Redis/Memcached)

**When to use caching:**
- Data that's read frequently but changes infrequently
- Expensive computations (e.g., aggregations, ML predictions)
- External API responses
- Session data
- Rate limiting counters

#### Redis Setup

```bash
# Install Redis
# Ubuntu/Debian
sudo apt-get install redis-server

# macOS
brew install redis

# Start Redis
redis-server

# Test connection
redis-cli ping  # Should return "PONG"
```

#### Pattern 1: Cache-Aside (Lazy Loading)

**Most common pattern: Check cache first, load from DB on miss**

**Python (Flask + Redis) Example:**

```python
import redis
import json
from flask import Flask, jsonify

app = Flask(__name__)
redis_client = redis.Redis(host='localhost', port=6379, decode_responses=True)

@app.route('/api/user/<int:user_id>')
def get_user_profile(user_id):
    # Step 1: Check cache first
    cache_key = f"user_profile:{user_id}"
    cached = redis_client.get(cache_key)

    if cached:
        # Cache hit (1-2ms)
        print("Cache HIT")
        return jsonify(json.loads(cached))

    # Step 2: Cache miss - fetch from database
    print("Cache MISS - querying database")
    user = db.query(f"SELECT * FROM users WHERE id = {user_id}")  # 50-200ms

    # Step 3: Store in cache for 5 minutes
    redis_client.setex(cache_key, 300, json.dumps(user))

    return jsonify(user)

# Performance:
# - First request: 150ms (database query + cache write)
# - Subsequent requests: 2ms (cache hit)
# - 75x faster for cached requests
```

**Node.js (Express + Redis) Example:**

```javascript
const express = require('express');
const redis = require('redis');

const app = express();
const redisClient = redis.createClient();

app.get('/api/user/:userId', async (req, res) => {
  const userId = req.params.userId;
  const cacheKey = `user_profile:${userId}`;

  try {
    // Check cache
    const cached = await redisClient.get(cacheKey);
    if (cached) {
      console.log('Cache HIT');
      return res.json(JSON.parse(cached));
    }

    // Cache miss - query database
    console.log('Cache MISS');
    const user = await db.query('SELECT * FROM users WHERE id = ?', [userId]);

    // Cache for 5 minutes
    await redisClient.setEx(cacheKey, 300, JSON.stringify(user));

    res.json(user);
  } catch (error) {
    res.status(500).json({ error: 'Internal server error' });
  }
});
```

**Cache invalidation (when data changes):**

```python
@app.route('/api/user/<int:user_id>', methods=['PUT'])
def update_user_profile(user_id):
    # Update database
    db.update_user(user_id, request.json)

    # Invalidate cache
    cache_key = f"user_profile:{user_id}"
    redis_client.delete(cache_key)

    return jsonify({"status": "updated"})
```

**Impact:** 50-100x faster for frequently accessed data

---

#### Pattern 2: Write-Through Cache

**Write to cache and database simultaneously**

```python
def update_user_profile(user_id, data):
    # Write to database
    db.update_user(user_id, data)

    # Write to cache immediately
    cache_key = f"user_profile:{user_id}"
    redis_client.setex(cache_key, 300, json.dumps(data))

    return data
```

**Pros:** Cache is always up-to-date
**Cons:** Slower writes (two operations)

---

#### Pattern 3: Session Storage

**Use Redis for fast session storage**

**Python (Flask-Session):**

```python
from flask import Flask, session
from flask_session import Session
import redis

app = Flask(__name__)
app.config['SESSION_TYPE'] = 'redis'
app.config['SESSION_REDIS'] = redis.Redis(host='localhost', port=6379)
Session(app)

@app.route('/login', methods=['POST'])
def login():
    # Store session in Redis (not database)
    session['user_id'] = 123
    session['username'] = 'john'
    return jsonify({"status": "logged in"})

# Impact: 20x faster than database-backed sessions
```

**Node.js (connect-redis):**

```javascript
const session = require('express-session');
const RedisStore = require('connect-redis')(session);
const redisClient = require('redis').createClient();

app.use(session({
  store: new RedisStore({ client: redisClient }),
  secret: 'your-secret-key',
  resave: false,
  saveUninitialized: false,
  cookie: { maxAge: 86400000 }  // 24 hours
}));
```

**Impact:** 10-20x faster than database sessions

---

#### Pattern 4: Rate Limiting

**Use Redis to track API request counts**

```python
from flask import Flask, request, jsonify
import redis

app = Flask(__name__)
redis_client = redis.Redis(host='localhost', port=6379)

def rate_limit(limit=100, window=60):
    """
    Rate limiter: Allow `limit` requests per `window` seconds
    """
    def decorator(f):
        def wrapper(*args, **kwargs):
            # Get client IP
            client_ip = request.remote_addr
            key = f"rate_limit:{client_ip}"

            # Increment counter
            current = redis_client.incr(key)

            # Set expiration on first request
            if current == 1:
                redis_client.expire(key, window)

            # Check if over limit
            if current > limit:
                return jsonify({"error": "Rate limit exceeded"}), 429

            return f(*args, **kwargs)
        return wrapper
    return decorator

@app.route('/api/data')
@rate_limit(limit=100, window=60)  # 100 requests per minute
def get_data():
    return jsonify({"data": "..."})
```

**Impact:** Prevents abuse, protects backend from overload

---

### CDN Configuration

**Problem:** Every request hits your origin server, even for static assets

**Solution:** Configure CDN to cache static assets at edge locations

#### Nginx Cache Headers

```nginx
# /etc/nginx/sites-available/yoursite

server {
    listen 443 ssl http2;
    server_name yoursite.com;

    # Static assets: Aggressive caching (1 year)
    location ~* \.(jpg|jpeg|png|gif|webp|avif|ico|svg)$ {
        expires 1y;
        add_header Cache-Control "public, max-age=31536000, immutable";
        add_header Vary "Accept";  # For content negotiation (WebP/AVIF)
    }

    location ~* \.(css|js)$ {
        expires 1y;
        add_header Cache-Control "public, max-age=31536000, immutable";

        # Enable compression
        gzip on;
        gzip_types text/css application/javascript;
        brotli on;
        brotli_types text/css application/javascript;
    }

    # Fonts: Long cache (1 year) + CORS
    location ~* \.(woff|woff2|ttf|eot)$ {
        expires 1y;
        add_header Cache-Control "public, max-age=31536000, immutable";
        add_header Access-Control-Allow-Origin "*";  # Allow cross-origin
    }

    # HTML: No cache (always check server)
    location ~* \.(html)$ {
        expires -1;
        add_header Cache-Control "no-cache, must-revalidate";
        add_header Pragma "no-cache";
    }

    # API responses: Short cache with stale-while-revalidate
    location /api/ {
        add_header Cache-Control "max-age=60, stale-while-revalidate=600";
        # Cached for 60s, serve stale for up to 10 minutes while revalidating

        proxy_pass http://backend;
    }
}
```

#### Apache Cache Headers

```apache
# .htaccess

# Enable caching
<IfModule mod_expires.c>
    ExpiresActive On

    # Images
    ExpiresByType image/jpeg "access plus 1 year"
    ExpiresByType image/png "access plus 1 year"
    ExpiresByType image/webp "access plus 1 year"
    ExpiresByType image/svg+xml "access plus 1 year"

    # CSS and JavaScript
    ExpiresByType text/css "access plus 1 year"
    ExpiresByType application/javascript "access plus 1 year"

    # Fonts
    ExpiresByType font/woff2 "access plus 1 year"
    ExpiresByType font/woff "access plus 1 year"

    # HTML (no cache)
    ExpiresByType text/html "access plus 0 seconds"
</IfModule>

<IfModule mod_headers.c>
    # Add Cache-Control headers
    <FilesMatch "\.(jpg|jpeg|png|gif|webp|avif|svg)$">
        Header set Cache-Control "max-age=31536000, public, immutable"
    </FilesMatch>

    <FilesMatch "\.(css|js)$">
        Header set Cache-Control "max-age=31536000, public, immutable"
    </FilesMatch>

    <FilesMatch "\.(html)$">
        Header set Cache-Control "no-cache, must-revalidate"
    </FilesMatch>
</IfModule>
```

#### Cloudflare Page Rules

```
# Cloudflare Dashboard → Page Rules

# Cache everything for static assets
Pattern: *.yoursite.com/static/*
Settings:
  - Cache Level: Cache Everything
  - Edge Cache TTL: 1 month
  - Browser Cache TTL: 1 year

# Bypass cache for API
Pattern: *.yoursite.com/api/*
Settings:
  - Cache Level: Bypass
```

**Impact:**
- 90-95% reduction in origin requests
- 50-200ms faster for users (served from edge)
- Lower server costs (fewer origin hits)

---

### HTTP/2 and HTTP/3 Adoption

**Benefits:**
- Multiplexing: Multiple requests over single connection
- Header compression: Smaller overhead
- Server push: Proactively send assets
- Faster TLS handshake (HTTP/3 with QUIC)

#### Enable HTTP/2 (Nginx)

```nginx
server {
    listen 443 ssl http2;  # Enable HTTP/2
    server_name yoursite.com;

    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;

    # HTTP/2 Server Push (optional, use sparingly)
    location = /index.html {
        http2_push /styles/critical.css;
        http2_push /js/app.js;
    }
}
```

#### Enable HTTP/3 (Nginx with QUIC)

```nginx
server {
    listen 443 ssl http2;
    listen 443 http3 reuseport;  # Enable HTTP/3

    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;

    # Advertise HTTP/3 support
    add_header Alt-Svc 'h3=":443"; ma=86400';
}
```

**Impact:** 30-50% faster for multiple resources (especially on high-latency networks)

---

### Cold Start Mitigation (Serverless)

**Problem:** AWS Lambda, Google Cloud Functions, Azure Functions have 1-3s cold start penalty

#### Solution 1: Reuse Connections

```javascript
// ❌ BAD: Create new database connection on every invocation
exports.handler = async (event) => {
    const db = await connectToDatabase();  // 1-2s cold start penalty
    const result = await db.query('SELECT * FROM users');
    await db.close();
    return result;
};

// ✅ GOOD: Reuse connection across invocations
let db;

exports.handler = async (event) => {
    if (!db) {
        db = await connectToDatabase();  // Only on cold start
    }
    const result = await db.query('SELECT * FROM users');
    return result;
    // Don't close connection - reuse on next invocation
};
```

#### Solution 2: Provisioned Concurrency (AWS Lambda)

```yaml
# serverless.yml
functions:
  api:
    handler: handler.main
    provisionedConcurrency: 5  # Keep 5 warm instances
```

**Cost:** ~$15/month per warm instance
**Benefit:** Eliminates cold starts for most requests

#### Solution 3: Keep Functions Warm

```javascript
// Scheduled pinger (runs every 5 minutes)
exports.pinger = async () => {
    // Invoke main function to keep it warm
    await lambda.invoke({
        FunctionName: 'myFunction',
        InvocationType: 'RequestResponse'
    });
};
```

**Impact:** Eliminates 1-3s cold start penalty

---

### Compression

**Enable Brotli (better than gzip)**

#### Nginx with Brotli

```nginx
http {
    # Brotli compression (install nginx-module-brotli)
    brotli on;
    brotli_comp_level 6;  # 1-11, higher = better compression but slower
    brotli_types
        text/plain
        text/css
        text/xml
        text/javascript
        application/json
        application/javascript
        application/xml+rss
        image/svg+xml;

    # Fallback to gzip for older browsers
    gzip on;
    gzip_vary on;
    gzip_comp_level 6;
    gzip_types
        text/plain
        text/css
        text/xml
        text/javascript
        application/json
        application/javascript;
}
```

#### Express.js with Compression

```javascript
const compression = require('compression');
const express = require('express');

const app = express();

// Enable compression (gzip)
app.use(compression({
    level: 6,  // Compression level (1-9)
    threshold: 1024,  // Only compress responses > 1KB
    filter: (req, res) => {
        // Don't compress images (already compressed)
        if (req.headers['x-no-compression']) {
            return false;
        }
        return compression.filter(req, res);
    }
}));
```

**Compression ratios:**
- **Brotli:** 20-30% smaller than gzip
- **Gzip:** 70-80% size reduction

**Impact:** 20-30% smaller transfer size, 5-10% faster TTFB

---

### Connection Pooling

**Problem:** Creating new database connections is expensive (50-200ms per connection)

**Solution:** Reuse a pool of connections

#### PostgreSQL (Node.js with pg)

```javascript
const { Pool } = require('pg');

// ❌ BAD: Create new connection for each query
async function getUser(userId) {
    const client = new Client({ connectionString: '...' });
    await client.connect();  // 50-200ms connection overhead
    const result = await client.query('SELECT * FROM users WHERE id = $1', [userId]);
    await client.end();
    return result.rows[0];
}

// ✅ GOOD: Use connection pool
const pool = new Pool({
    connectionString: process.env.DATABASE_URL,
    max: 20,  // Maximum 20 connections in pool
    idleTimeoutMillis: 30000,
    connectionTimeoutMillis: 2000,
});

async function getUser(userId) {
    // Reuse connection from pool (1-2ms)
    const result = await pool.query('SELECT * FROM users WHERE id = $1', [userId]);
    return result.rows[0];
}
```

#### Python (SQLAlchemy)

```python
from sqlalchemy import create_engine
from sqlalchemy.pool import QueuePool

# Connection pool
engine = create_engine(
    'postgresql://user:pass@localhost/db',
    poolclass=QueuePool,
    pool_size=20,  # Keep 20 connections
    max_overflow=10,  # Allow 10 additional connections if needed
    pool_recycle=3600,  # Recycle connections after 1 hour
)

# Reuse connections
def get_user(user_id):
    with engine.connect() as conn:
        result = conn.execute("SELECT * FROM users WHERE id = %s", user_id)
        return result.fetchone()
```

**Impact:** 50-200ms faster per query (eliminates connection overhead)

---

### Verification Checklist

After implementing backend optimizations:

**TTFB Breakdown:**
```bash
# Before optimization
$ curl -w "@curl-format.txt" -o /dev/null -s https://yoursite.com
time_starttransfer: 3.67s (TTFB) ❌

# After optimization
$ curl -w "@curl-format.txt" -o /dev/null -s https://yoursite.com
time_starttransfer: 0.42s (TTFB) ✅
# 88% improvement!
```

**Database Performance:**
- [ ] No N+1 queries (check with ORM query logging)
- [ ] All foreign keys have indexes
- [ ] Slow query log enabled and monitored
- [ ] Only fetching needed columns

**Caching:**
- [ ] Redis/Memcached installed and configured
- [ ] Cache hit ratio >80% for frequently accessed data
- [ ] Cache invalidation strategy implemented

**Infrastructure:**
- [ ] CDN configured for static assets
- [ ] Cache-Control headers set correctly
- [ ] HTTP/2 or HTTP/3 enabled
- [ ] Compression (Brotli or gzip) enabled

**Serverless (if applicable):**
- [ ] Database connections reused across invocations
- [ ] Provisioned concurrency for critical functions
- [ ] Cold start monitoring in place

---

## Image Optimization

**Critical for:** LCP (Largest Contentful Paint) and page weight reduction

### Modern Image Formats

**Format comparison:**

| Format | File Size | Browser Support | Use Case |
|--------|-----------|-----------------|----------|
| JPEG   | Baseline  | 100%           | Photos (fallback) |
| WebP   | 30% smaller | 97%          | Modern browsers |
| AVIF   | 50% smaller | 89%          | Cutting edge (best quality/size) |
| SVG    | Tiny      | 100%           | Logos, icons |

#### Converting to Modern Formats

```bash
# Install tools
# Ubuntu/Debian
sudo apt-get install webp imagemagick libavif-bin

# macOS
brew install webp imagemagick libavif

# Convert JPEG → WebP (30% smaller)
cwebp -q 85 hero.jpg -o hero.webp

# Convert JPEG → AVIF (50% smaller than JPEG)
avifenc -s 5 hero.jpg hero.avif

# Batch conversion
for img in *.jpg; do
    cwebp -q 85 "$img" -o "${img%.jpg}.webp"
    avifenc -s 5 "$img" "${img%.jpg}.avif"
done

# ImageMagick (alternative)
magick hero.jpg -quality 85 hero.webp
magick hero.jpg -quality 85 hero.avif
```

#### Serving Modern Formats with `<picture>`

```html
<picture>
  <!-- Serve AVIF to browsers that support it (50% smaller) -->
  <source srcset="hero.avif" type="image/avif">

  <!-- Fallback to WebP for other modern browsers (30% smaller) -->
  <source srcset="hero.webp" type="image/webp">

  <!-- Fallback to JPEG for older browsers -->
  <img src="hero.jpg" alt="Hero" width="1200" height="600">
</picture>
```

**Impact:** 30-50% smaller file size, faster LCP

---

### Responsive Images

**Problem:** Serving desktop-sized images to mobile devices wastes bandwidth

**Solution:** Use `srcset` and `sizes` attributes

```html
<!-- ❌ BAD: Same image for all screen sizes -->
<img src="hero-large.jpg" alt="Hero">
<!-- Mobile users download 2MB desktop image for 375px screen -->

<!-- ✅ GOOD: Responsive images with srcset -->
<img
    src="hero-800.jpg"
    srcset="
        hero-400.jpg 400w,
        hero-800.jpg 800w,
        hero-1200.jpg 1200w,
        hero-1600.jpg 1600w
    "
    sizes="
        (max-width: 600px) 400px,
        (max-width: 900px) 800px,
        (max-width: 1200px) 1200px,
        1600px
    "
    alt="Hero"
    width="1600"
    height="900"
>
<!-- Mobile users download only 400px image (150KB vs 2MB) -->
```

**Generate responsive images:**

```bash
# Generate multiple sizes
convert hero.jpg -resize 400x hero-400.jpg
convert hero.jpg -resize 800x hero-800.jpg
convert hero.jpg -resize 1200x hero-1200.jpg
convert hero.jpg -resize 1600x hero-1600.jpg

# Optimize each size
jpegoptim --strip-all --max=85 hero-*.jpg
```

**Impact:** 70-90% smaller downloads for mobile users

---

### Image Dimensions (Prevents CLS)

**Problem:** Images without dimensions cause layout shift

```html
<!-- ❌ BAD: No dimensions, causes CLS -->
<img src="hero.jpg" alt="Hero">
<!-- Page loads → Text appears → Image loads → Text shifts down → CLS! -->

<!-- ✅ GOOD: Explicit dimensions prevent CLS -->
<img src="hero.jpg" alt="Hero" width="1200" height="600">
<!-- Browser reserves space before image loads → No shift -->

<!-- ✅ BETTER: Responsive with aspect-ratio -->
<img src="hero.jpg" alt="Hero" style="aspect-ratio: 16/9; width: 100%;">
```

**CSS for responsive images with dimensions:**

```css
img {
    max-width: 100%;
    height: auto;
    /* aspect-ratio preserved from width/height attributes */
}
```

**Impact:** Reduces CLS by 50-80%

---

### Lazy Loading

**Load images only when needed**

```html
<!-- Images above fold: Eager loading -->
<img src="hero.jpg" alt="Hero" loading="eager" fetchpriority="high">

<!-- Images below fold: Lazy loading -->
<img src="content-1.jpg" alt="Content 1" loading="lazy">
<img src="content-2.jpg" alt="Content 2" loading="lazy">
```

**JavaScript lazy loading (for older browsers):**

```javascript
// Intersection Observer for lazy loading
const images = document.querySelectorAll('img[data-src]');

const imageObserver = new IntersectionObserver((entries, observer) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            const img = entry.target;
            img.src = img.dataset.src;
            img.removeAttribute('data-src');
            observer.unobserve(img);
        }
    });
});

images.forEach(img => imageObserver.observe(img));
```

**Impact:** 40-60% reduction in initial page weight

---

### Image Compression

**Optimize images without quality loss**

```bash
# JPEG optimization (lossless)
jpegoptim --strip-all hero.jpg
# Removes metadata, ~10% size reduction

# JPEG optimization (lossy, better compression)
jpegoptim --max=85 --strip-all hero.jpg
# Quality 85 is visually identical, ~30% size reduction

# PNG optimization (lossless)
optipng -o7 logo.png
# Maximum optimization, ~20% size reduction

# PNG → JPEG for photos (huge savings)
convert photo.png -quality 85 photo.jpg
# 80-90% size reduction for photos

# WebP optimization
cwebp -q 85 -m 6 -mt hero.jpg -o hero.webp
# -m 6: Maximum compression effort
# -mt: Multi-threading
```

**Automated optimization (build process):**

```json
{
    "scripts": {
        "optimize-images": "find ./public/images -type f \\( -name '*.jpg' -o -name '*.png' \\) -exec imageoptim {} \\;"
    }
}
```

**Impact:** 20-50% size reduction (lossless), 50-80% (lossy)

---

### CDN for Images

**Use image CDN for automatic optimization**

**Cloudinary example:**

```html
<!-- Original image URL -->
<img src="https://yoursite.com/images/hero.jpg" alt="Hero">

<!-- Cloudinary: Automatic format, compression, and resizing -->
<img src="https://res.cloudinary.com/yourcloud/image/upload/f_auto,q_auto,w_800/hero.jpg" alt="Hero">
<!-- f_auto: Automatic format (WebP/AVIF for modern browsers)
     q_auto: Automatic quality optimization
     w_800: Resize to 800px width -->
```

**imgix example:**

```html
<img src="https://yoursite.imgix.net/hero.jpg?auto=format,compress&w=800" alt="Hero">
```

**Benefits:**
- Automatic format conversion (WebP/AVIF)
- Automatic compression
- Responsive images via URL parameters
- Global CDN delivery

**Impact:** 50-70% smaller images, 100-300ms faster loading

---

## JavaScript Optimization

### Code Splitting

**Problem:** Loading entire app bundle upfront (500KB+) slows initial load

**Solution:** Split code by route or component

#### React with Lazy Loading

```javascript
import { lazy, Suspense } from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';

// ❌ BAD: Loading everything upfront
import Dashboard from './Dashboard';
import Settings from './Settings';
import Reports from './Reports';

// Initial bundle: 500KB (all routes included)

// ✅ GOOD: Route-based code splitting
const Dashboard = lazy(() => import('./Dashboard'));
const Settings = lazy(() => import('./Settings'));
const Reports = lazy(() => import('./Reports'));

// Initial bundle: 100KB (only shell + current route)
// Other routes loaded on demand

function App() {
    return (
        <BrowserRouter>
            <Suspense fallback={<LoadingSpinner />}>
                <Routes>
                    <Route path="/dashboard" element={<Dashboard />} />
                    <Route path="/settings" element={<Settings />} />
                    <Route path="/reports" element={<Reports />} />
                </Routes>
            </Suspense>
        </BrowserRouter>
    );
}
```

#### Next.js (Automatic Code Splitting)

```javascript
// Next.js automatically code splits by route

// pages/dashboard.tsx - Loaded only when visiting /dashboard
export default function Dashboard() {
    return <div>Dashboard</div>;
}

// Dynamic import for components
import dynamic from 'next/dynamic';

const HeavyChart = dynamic(() => import('./HeavyChart'), {
    loading: () => <p>Loading chart...</p>,
    ssr: false  // Don't render on server (client-only)
});

export default function Analytics() {
    return (
        <div>
            <h1>Analytics</h1>
            <HeavyChart />  {/* Loaded only when component renders */}
        </div>
    );
}
```

**Impact:** 30-50% smaller initial bundle

---

### Tree Shaking

**Remove unused code from bundles**

#### Enable Tree Shaking

```json
// package.json
{
    "sideEffects": false  // Enable aggressive tree shaking
}

// Or specify files with side effects
{
    "sideEffects": ["*.css", "*.scss", "src/polyfills.js"]
}
```

#### Import Only What You Need

```javascript
// ❌ BAD: Imports entire library (200KB)
import _ from 'lodash';
const result = _.debounce(fn, 300);

// ✅ GOOD: Import only needed function (ES modules, 5KB)
import { debounce } from 'lodash-es';
const result = debounce(fn, 300);

// ✅ ALSO GOOD: Individual module import
import debounce from 'lodash/debounce';
const result = debounce(fn, 300);
```

**Webpack Configuration:**

```javascript
// webpack.config.js
module.exports = {
    mode: 'production',  // Enables tree shaking
    optimization: {
        usedExports: true,  // Mark unused exports
        minimize: true,     // Remove unused code
        sideEffects: true,  // Respect package.json sideEffects
    }
};
```

**Impact:** 40-60% smaller bundles

---

### Bundle Analysis

**Identify large dependencies**

```bash
# Install webpack-bundle-analyzer
npm install --save-dev webpack-bundle-analyzer

# Run build with analysis
npm run build -- --analyze
```

**Webpack configuration:**

```javascript
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

module.exports = {
    plugins: [
        new BundleAnalyzerPlugin({
            analyzerMode: 'static',
            openAnalyzer: true,
            reportFilename: 'bundle-report.html'
        })
    ]
};
```

**What to look for:**
- Large dependencies (>50KB) that are barely used
- Duplicate dependencies (same library, different versions)
- Unused exports
- Opportunities for code splitting

**Impact:** Helps identify 20-40% of unnecessary code

---

### Dynamic Imports

**Load code only when needed**

```javascript
// ❌ BAD: Loading heavy library upfront
import Chart from 'chart.js';  // 200KB

function Analytics() {
    const [showChart, setShowChart] = useState(false);

    return (
        <div>
            <button onClick={() => setShowChart(true)}>Show Chart</button>
            {showChart && <Chart data={data} />}
        </div>
    );
}

// ✅ GOOD: Dynamic import (load only when needed)
function Analytics() {
    const [showChart, setShowChart] = useState(false);
    const [ChartComponent, setChartComponent] = useState(null);

    const loadChart = async () => {
        const { default: Chart } = await import('chart.js');  // Load on click
        setChartComponent(() => Chart);
        setShowChart(true);
    };

    return (
        <div>
            <button onClick={loadChart}>Show Chart</button>
            {showChart && ChartComponent && <ChartComponent data={data} />}
        </div>
    );
}
```

**Impact:** Reduces initial bundle by size of dynamically loaded code

---

## CSS Optimization

### Critical CSS Extraction

**Inline above-fold CSS, defer below-fold CSS**

```html
<head>
    <!-- ✅ GOOD: Inline critical CSS -->
    <style>
        /* Critical above-fold styles (5-10KB) */
        body { margin: 0; font-family: sans-serif; }
        .header { background: #333; color: white; }
        .hero { height: 100vh; background: url('hero.jpg'); }
    </style>

    <!-- Load non-critical CSS asynchronously -->
    <link rel="preload" href="styles.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
    <noscript><link rel="stylesheet" href="styles.css"></noscript>
</head>
```

**Extract critical CSS automatically:**

```bash
# Using Critical (Node.js tool)
npm install -g critical

critical index.html --base ./public --inline --minify > index-optimized.html
```

**Impact:** 100-300ms faster FCP (First Contentful Paint)

---

### Unused CSS Removal

**Remove CSS not used on page**

```bash
# Using PurgeCSS
npm install --save-dev @fullhuman/postcss-purgecss

# postcss.config.js
module.exports = {
    plugins: [
        require('@fullhuman/postcss-purgecss')({
            content: ['./src/**/*.html', './src/**/*.js'],
            defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || []
        })
    ]
};
```

**Tailwind CSS (built-in purging):**

```javascript
// tailwind.config.js
module.exports = {
    content: [
        './src/**/*.{html,js,jsx,ts,tsx}',
    ],
    // Tailwind automatically removes unused classes
};
```

**Impact:** 50-90% smaller CSS files

---

### CSS-in-JS Optimization

**Extract static CSS at build time**

```javascript
// ❌ BAD: Runtime CSS-in-JS (slower)
import styled from 'styled-components';

const Button = styled.button`
    background: blue;
    color: white;
`;
// Generates CSS at runtime in browser

// ✅ BETTER: Zero-runtime CSS-in-JS
import { styled } from '@linaria/react';

const Button = styled.button`
    background: blue;
    color: white;
`;
// CSS extracted at build time, no runtime overhead
```

**Impact:** 20-50ms faster initial render

---

## Resource Loading Optimization

### Preload Critical Resources

```html
<head>
    <!-- Preload LCP image -->
    <link rel="preload" as="image" href="hero.webp" fetchpriority="high">

    <!-- Preload critical fonts -->
    <link rel="preload" href="/fonts/main.woff2" as="font" type="font/woff2" crossorigin>

    <!-- Preload critical CSS -->
    <link rel="preload" as="style" href="critical.css">
</head>
```

**Impact:** 100-300ms faster LCP

---

### Preconnect to Critical Origins

```html
<head>
    <!-- Preconnect to critical third-party origins -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link rel="preconnect" href="https://cdn.yoursite.com">

    <!-- DNS-prefetch for less critical origins -->
    <link rel="dns-prefetch" href="https://analytics.google.com">
</head>
```

**Impact:** 100-500ms saved per critical resource

---

### Priority Hints (fetchpriority)

```html
<!-- High priority for LCP image -->
<img src="hero.jpg" alt="Hero" fetchpriority="high" loading="eager">

<!-- Low priority for below-fold images -->
<img src="footer-logo.jpg" alt="Footer" fetchpriority="low" loading="lazy">

<!-- High priority for critical script -->
<script src="app.js" fetchpriority="high" defer></script>
```

**Impact:** 50-200ms faster LCP

---

## Caching Strategies

### HTTP Caching

See [CDN Configuration](#cdn-configuration) section for detailed cache headers.

### Service Worker Caching

**Basic service worker with caching:**

```javascript
// sw.js
const CACHE_NAME = 'v1';
const urlsToCache = [
    '/',
    '/styles.css',
    '/app.js',
    '/logo.png'
];

// Install: Cache static assets
self.addEventListener('install', (event) => {
    event.waitUntil(
        caches.open(CACHE_NAME)
            .then(cache => cache.addAll(urlsToCache))
    );
});

// Fetch: Cache-first strategy
self.addEventListener('fetch', (event) => {
    event.respondWith(
        caches.match(event.request)
            .then(response => response || fetch(event.request))
    );
});
```

**Advanced caching with Workbox:**

```javascript
import { precacheAndRoute } from 'workbox-precaching';
import { registerRoute } from 'workbox-routing';
import { CacheFirst, NetworkFirst, StaleWhileRevalidate } from 'workbox-strategies';

// Precache build assets
precacheAndRoute(self.__WB_MANIFEST);

// Images: CacheFirst
registerRoute(
    ({ request }) => request.destination === 'image',
    new CacheFirst({ cacheName: 'images', plugins: [/* expiration */] })
);

// API: NetworkFirst
registerRoute(
    ({ url }) => url.pathname.startsWith('/api/'),
    new NetworkFirst({ cacheName: 'api' })
);
```

**Impact:** Instant repeat visits, offline support

---

## Summary Checklist

### Backend Optimization
- [ ] No N+1 database queries
- [ ] All foreign keys indexed
- [ ] Redis/Memcached caching implemented
- [ ] CDN configured for static assets
- [ ] HTTP/2 or HTTP/3 enabled
- [ ] Compression enabled (Brotli or gzip)
- [ ] Connection pooling configured
- [ ] TTFB <800ms

### Image Optimization
- [ ] Modern formats (WebP/AVIF) used
- [ ] Responsive images with srcset
- [ ] All images have width/height attributes
- [ ] Lazy loading for below-fold images
- [ ] LCP image preloaded with fetchpriority="high"

### JavaScript Optimization
- [ ] Code splitting by route
- [ ] Tree shaking enabled
- [ ] Bundle size analyzed
- [ ] Large dependencies identified and optimized
- [ ] Dynamic imports for heavy components

### CSS Optimization
- [ ] Critical CSS inlined
- [ ] Unused CSS removed
- [ ] CSS files minified
- [ ] Non-critical CSS deferred

### Resource Loading
- [ ] Critical resources preloaded
- [ ] Third-party origins preconnected
- [ ] Priority hints used for LCP resources

### Caching
- [ ] HTTP cache headers configured
- [ ] Service worker implemented
- [ ] CDN caching enabled
- [ ] Cache invalidation strategy in place

---

**Performance targets:**
- TTFB: <800ms ✅
- LCP: <2.5s ✅
- CLS: <0.1 ✅
- INP: <200ms ✅

**Next:** See [core-web-vitals.md](core-web-vitals.md) for detailed metric optimization strategies.