Fastly CDN Setup for High-Load Projects
When your site starts slowing down due to traffic spikes and cache invalidation takes minutes, standard CDNs fall short. We often see projects where content updates every few seconds but the cache lives for an hour—resulting in stale data. Fastly solves this with instant invalidation (<150 ms across its network) and programmable edge logic via VCL and Compute@Edge. It’s the choice for projects needing full caching control and flexibility.
We use Fastly for dynamic content: news portals, e-commerce, SaaS platforms. After setup, the HIT-ratio reaches 95%, reducing backend load by 80%. Below we break down key features and practical configuration examples.
Why Fastly Outperforms Other CDNs?
| Feature | Fastly | Cloudflare | CloudFront |
|---|---|---|---|
| Invalidation | <150 ms | 1–30 s | 1–5 min |
| Edge programming | VCL + WASM | Workers (JS) | Functions (JS) |
| Tag invalidation | Yes (Surrogate-Key) | No | No |
| Real-time logs | Yes | Yes | Via S3 |
| Streaming | Excellent | Good | Good |
Fastly invalidates 10x faster than CloudFront and 20x faster than Cloudflare. And Surrogate-Key tag invalidation lets you purge only related pages without affecting the whole site.
How We Set Up Fastly CDN: Phases
Setup proceeds in phases:
- Analysis — audit current architecture, traffic, and caching requirements.
- Design — develop VCL logic: which URLs to cache, which to pass, how to handle cookies.
- Implementation — deploy the service via Terraform or API, write VCL rules, configure Surrogate-Key on the backend.
- Testing — verify invalidation, performance, caching correctness.
- Deployment — enable CDN on production, monitor and optimize.
| Phase | Duration | Result |
|---|---|---|
| Analysis | 1–2 days | Architecture diagram, requirements |
| Design | 1 day | VCL logic, invalidation scheme |
| Implementation | 1–2 days | Working service in Fastly |
| Testing | 1 day | Performance report |
| Deployment | 0.5 day | CDN enabled on production |
How Tagged Invalidation (Surrogate-Key) Works
This is Fastly’s key advantage. You can assign one or more tags (keys) to each page or object. When content updates, send an invalidation request for only those tags—cache clears instantly without a Purge All.
Example in Laravel:
// Laravel: add Surrogate-Key header to response
public function show(Product $product): Response
{
$response = response()->view('products.show', compact('product'));
// Tags for this page
$surrogateKeys = [
"product:{$product->id}",
"category:{$product->category_id}",
"brand:{$product->brand_id}",
];
return $response->header(
'Surrogate-Key',
implode(' ', $surrogateKeys)
);
}
// When product updates — invalidate only related pages
class ProductObserver
{
public function saved(Product $product): void
{
Http::withHeaders([
'Fastly-Key' => config('services.fastly.api_key'),
])->post(
"https://api.fastly.com/service/{$serviceId}/purge/product:{$product->id}"
);
}
}
Implementation details
Note that the Fastly API key must be stored securely. We recommend using Laravel Vault or environment variables.VCL — Custom Caching Logic
Fastly executes VCL on every request. It’s more powerful than Workers for network operations. Here’s a typical set of rules we use:
// Custom VCL: vcl_recv — handle incoming request
sub vcl_recv {
// Remove marketing parameters from cache key
set req.url = regsubreplace(req.url,
"\?(.*&)?(utm_source|utm_medium|utm_campaign|fbclid|gclid)=[^&]*(&|$)",
"?"
);
set req.url = regsub(req.url, "\?$", "");
// Do not cache authenticated users
if (req.http.Cookie ~ "laravel_session") {
return(pass);
}
// Do not cache /admin/ and /api/
if (req.url ~ "^/(admin|area51|api)/") {
return(pass);
}
// Normalize Accept-Encoding
if (req.http.Accept-Encoding ~ "br") {
set req.http.Accept-Encoding = "br";
} elsif (req.http.Accept-Encoding ~ "gzip") {
set req.http.Accept-Encoding = "gzip";
} else {
unset req.http.Accept-Encoding;
}
}
sub vcl_backend_response {
// Static assets — one year
if (bereq.url ~ "\.(js|css|woff2|webp|avif)$") {
set beresp.ttl = 365d;
set beresp.http.Cache-Control = "public, max-age=31536000, immutable";
}
// HTML pages — 5 minutes
if (beresp.http.Content-Type ~ "text/html") {
set beresp.ttl = 5m;
set beresp.grace = 1h; // stale-while-revalidate
}
}
sub vcl_deliver {
// Debug header
if (obj.hits > 0) {
set resp.http.X-Cache = "HIT";
set resp.http.X-Cache-Hits = obj.hits;
} else {
set resp.http.X-Cache = "MISS";
}
}
VCL explanation
Note: in vcl_recv we normalize Accept-Encoding to avoid cache duplication for different encodings. This boosts HIT-ratio to 95%.Provisioning via Terraform
Fastly is fully managed via API or Terraform provider. Below is an example configuration with backend, gzip, and logging:
terraform {
required_providers {
fastly = {
source = "fastly/fastly"
version = "~> 5.0"
}
}
}
resource "fastly_service_vcl" "main" {
name = "example-production"
domain {
name = "example.ru"
}
backend {
address = "origin.example.ru"
name = "origin"
port = 443
use_ssl = true
ssl_cert_hostname = "origin.example.ru"
ssl_sni_hostname = "origin.example.ru"
connect_timeout = 5000
between_bytes_timeout = 30000
first_byte_timeout = 30000
}
gzip {
name = "gzip-policy"
content_types = ["text/html", "text/css", "application/javascript", "application/json"]
extensions = ["css", "js", "html", "json"]
}
logging_s3 {
name = "s3-logs"
bucket_name = "fastly-logs"
path = "/cdn/%Y/%m/%d/"
period = 3600
format = "%h %l %u %t \"%r\" %>s %b"
s3_access_key = var.aws_access_key
s3_secret_key = var.aws_secret_key
}
logging_elasticsearch {
name = "elasticsearch-logs"
index = "fastly-%{now}V"
url = "https://es.example.ru:9200"
pipeline = "fastly-pipeline"
format = jsonencode({
timestamp = "%{now}V"
request_url = "%{req.url}V"
status = "%{resp.status}V"
cache_status = "%{resp.http.X-Cache}V"
country = "%{client.geo.country_code}V"
duration_ms = "%D"
})
}
force_destroy = true
}
Instant Content Publishing
When publishing an article or product, simply call the API to invalidate only affected pages:
class ArticlePublishedListener
{
public function handle(ArticlePublished $event): void
{
$article = $event->article;
Http::withHeaders(['Fastly-Key' => config('services.fastly.api_key')])
->post("https://api.fastly.com/service/{$serviceId}/purge", [
'urls' => [
"https://example.ru/blog/{$article->slug}",
"https://example.ru/blog/",
"https://example.ru/",
]
]);
}
}
What’s Included in Fastly CDN Setup
- Audit of current architecture and traffic
- Development of VCL caching logic tailored to your project
- Configuration of Surrogate-Key tagged invalidation
- Integration with backend (Laravel, Next.js, Django, etc.)
- Setup of monitoring and logs (S3, Elasticsearch, Kafka)
- Documentation and team training
- Post-release support for 2 weeks
After setup, invalidation time is under 150 ms, HIT-ratio exceeds 95%, and backend load drops by 80%. For one project, monthly CDN costs decreased from $4,500 to $1,200, and page load speed improved by 40%. As noted in Fastly documentation, cache invalidation occurs in under 150 ms.
Timelines and Cost
Basic setup with VCL and tagged invalidation takes 2–3 days. For complex projects with custom rules, up to 5 days. Cost is determined individually after an audit. Get a consultation on Fastly CDN setup — contact us.
Common Fastly Setup Mistakes
- Missing Accept-Encoding normalization: different URL versions enter cache, reducing HIT-ratio.
- No cookie handling: pages with sessions are cached, causing data conflicts.
- Too long TTL for HTML without grace period: origin failure results in errors for users.
- Not using Surrogate-Key: invalidation happens site-wide instead of targeted.
Our engineers have 5+ years of Fastly experience and VCL certifications. We guarantee that after setup, your site will be fast and resilient. Order an audit of your current CDN architecture — and we’ll propose the optimal solution.







