Blog
February 25, 2025

Optimizing Content Performance with Scalar

Learn how to leverage Scalar's performance features to deliver lightning-fast content experiences to your users.

Yassine Zaanouni
Yassine Zaanouni
10 mins read

Optimizing Content Performance with Scalar

Learn how to leverage Scalar’s performance features to deliver lightning-fast content experiences to your users.

Why Content Performance Matters

In today’s digital landscape, user expectations for performance continue to rise. Research consistently shows that:

  • 53% of users abandon sites that take longer than 3 seconds to load
  • Each 100ms of latency can reduce conversion rates by up to 1%
  • Poor performance disproportionately affects users in emerging markets
  • Search engines factor load times into ranking algorithms

For content-heavy sites and applications, performance optimization begins with how content is structured, stored, and delivered. Scalar was built with performance as a core principle, providing tools that make it easy to deliver fast experiences without sacrificing content richness.

Content Delivery Architecture

Before diving into specific optimizations, let’s understand Scalar’s content delivery architecture:

┌───────────────┐ ┌───────────────┐ ┌───────────────┐
│ │ │ │ │ │
│ Content API │◄────►│ CDN Cache │◄────►│ Edge Cache │
│ │ │ │ │ │
└───────────────┘ └───────────────┘ └───────────────┘
▲ ▲ ▲
│ │ │
▼ ▼ ▼
┌───────────────┐ ┌───────────────┐ ┌───────────────┐
│ │ │ │ │ │
│ Database/Cache│ │ Client Cache │ │ Browser Cache │
│ │ │ │ │ │
└───────────────┘ └───────────────┘ └───────────────┘

This multi-layered approach provides numerous optimization opportunities. Let’s explore them:

1. Content Modeling for Performance

How you structure your content has a significant impact on performance. Follow these best practices:

Normalize Your Data Model

Properly normalized content models prevent duplication and improve query efficiency:

// Instead of duplicating author information in each post
const BlogPost = defineType({
name: 'blogPost',
fields: {
title: fields.text({ required: true }),
// Use a reference instead of embedding author data
author: fields.reference({
to: 'author',
required: true,
}),
// Other fields...
},
});
const Author = defineType({
name: 'author',
fields: {
name: fields.text({ required: true }),
bio: fields.richText(),
avatar: fields.image(),
},
});

Use Field Selection Wisely

Not all fields are needed in all contexts. Design your queries to fetch only what’s needed:

// Fetch just what's needed for a list view
const postSummaries = await scalar
.query('blogPost')
.select(['title', 'publishDate', 'slug'])
.orderBy({ publishDate: 'desc' })
.limit(10)
.exec();
// Fetch everything for a detail view
const fullPost = await scalar
.query('blogPost')
.where({ slug: 'performance-optimization' })
.include(['author', 'categories', 'relatedPosts'])
.first();

Intelligent Pagination

For large collections, implement pagination to limit payload size:

// Cursor-based pagination for optimal performance
const { items, nextCursor } = await scalar
.query('product')
.where({ category: 'electronics' })
.orderBy({ popularity: 'desc' })
.paginate({ cursor, limit: 20 });

2. Asset Optimization

Content performance isn’t just about data—media assets often account for the bulk of page weight.

Image Processing

Scalar provides powerful image optimization capabilities:

// In your content model
const Product = defineType({
name: 'product',
fields: {
// Configure image processing defaults
image: fields.image({
variants: {
thumbnail: { width: 200, height: 200 },
medium: { width: 600, height: 600 },
large: { width: 1200, height: 1200 },
},
defaultFormat: 'webp',
transformations: {
quality: 85,
smartCrop: true,
},
}),
},
});

When retrieving images, you can request specific variants or apply transformations on the fly:

// In your React component
function ProductCard({ product }) {
return (
<div className="product-card">
{/* Responsive images with srcset */}
<img
src={product.image.url({ variant: 'medium' })}
srcSet={`
${product.image.url({ variant: 'thumbnail' })} 200w,
${product.image.url({ variant: 'medium' })} 600w,
${product.image.url({ variant: 'large' })} 1200w
`}
sizes="(max-width: 600px) 200px, (max-width: 1200px) 600px, 1200px"
alt={product.name}
/>
</div>
);
}

Lazy Loading Media

Implement lazy loading for below-the-fold content:

// Using Scalar's React SDK for lazy-loaded images
import { Image } from '@scalar/react-components';
function ProductGallery({ products }) {
return (
<div className="product-gallery">
{products.map((product) => (
<Image
key={product.id}
src={product.image}
variant="medium"
lazyLoad
threshold={0.1} // Start loading when 10% visible
/>
))}
</div>
);
}

3. Caching Strategies

Proper caching dramatically improves content performance. Scalar provides several caching mechanisms:

CDN Configuration

Configure CDN caching in your Scalar project settings:

scalar.config.ts
export default defineConfig({
delivery: {
cdn: {
enabled: true,
cachePolicies: [
{
pattern: '/api/content/**',
maxAge: 3600, // 1 hour
sMaxAge: 86400, // 1 day
staleWhileRevalidate: true,
},
{
pattern: '/api/assets/**',
maxAge: 604800, // 7 days
immutable: true,
},
],
},
},
});

Runtime Cache Control

Adjust cache behavior at query time:

// Highly dynamic content - no caching
const liveScores = await scalar
.query('gameScore')
.where({ status: 'live' })
.cacheControl({ maxAge: 0 })
.exec();
// Semi-static content - short cache
const todaysPosts = await scalar
.query('blogPost')
.where({ publishDate: { $gte: today } })
.orderBy({ publishDate: 'desc' })
.cacheControl({ maxAge: 300 }) // 5 minutes
.exec();
// Archival content - long cache
const archiveContent = await scalar
.query('blogPost')
.where({ publishDate: { $lt: lastYear } })
.cacheControl({ maxAge: 604800 }) // 7 days
.exec();

Automatic Cache Invalidation

Scalar automatically invalidates caches when content changes, but you can also configure custom invalidation rules:

export default defineConfig({
caching: {
invalidation: {
rules: [
// When a product changes, invalidate collection pages
{
contentType: 'product',
invalidate: ['/api/collections/**'],
},
// When homepage content changes, invalidate the homepage
{
contentType: 'homepage',
invalidate: ['/api/content/homepage', '/'],
},
],
},
},
});

4. Edge Computing

For the ultimate in performance, Scalar supports edge computing capabilities:

Edge-Optimized API

Deploy Scalar’s API to edge locations worldwide:

scalar.config.ts
export default defineConfig({
deployment: {
type: 'edge',
regions: ['auto'], // Deploy to all edge regions
providers: {
// Configure your preferred edge provider
cloudflare: {
enabled: true,
},
},
},
});

Edge Middleware

Implement custom logic at the edge:

middleware.ts
import { createEdgeMiddleware } from '@scalar/edge';
export default createEdgeMiddleware({
async process(request, context) {
// Geo-based content customization
const country = request.headers.get('cf-ipcountry');
if (country) {
context.geo = { country };
}
// A/B testing at the edge
const testGroup = Math.random() < 0.5 ? 'A' : 'B';
context.experiments = { homePageVariant: testGroup };
return context;
},
});

5. Real-time Content Delivery

For dynamic applications, Scalar provides real-time capabilities that maintain high performance:

WebSocket Subscriptions

Subscribe to content changes with minimal overhead:

// In your client application
import { createClient } from '@scalar/client';
const client = createClient({
projectId: 'your-project-id',
realtime: true,
});
// Subscribe to changes
const unsubscribe = client
.subscribe('comment')
.where({ postId: currentPostId })
.orderBy({ createdAt: 'desc' })
.limit(10)
.on('update', (comments) => {
// Update UI with new comments
updateCommentsUI(comments);
});
// Later, when component unmounts
unsubscribe();

Optimized Delta Updates

When subscribing to large content objects, Scalar only transmits changes:

// Configure delta updates for specific content types
export default defineConfig({
realtime: {
deltaUpdates: {
enabled: true,
contentTypes: ['dashboardData', 'analytics', 'userProfile'],
},
},
});

6. Advanced Query Optimization

For complex data models, query optimization becomes crucial:

Indexing Strategy

Define indexes to support your common query patterns:

scalar.config.ts
export default defineConfig({
database: {
indexes: [
{
contentType: 'product',
fields: [
{ name: 'category', direction: 'asc' },
{ name: 'price', direction: 'asc' },
],
name: 'product_category_price',
},
{
contentType: 'blogPost',
fields: [
{ name: 'tags', direction: 'asc' },
{ name: 'publishDate', direction: 'desc' },
],
name: 'blogpost_tags_date',
},
],
},
});

Query Analysis

Use Scalar’s query analysis tools to identify slow queries:

Terminal window
# Enable query logging in development
scalar dev --query-logging=true
# Or in production configuration
export default defineConfig({
database: {
monitoring: {
queryLogging: {
enabled: true,
slowQueryThreshold: 500 // Log queries taking > 500ms
}
}
}
});

Materialized Views

For complex aggregations or reporting queries, use materialized views:

scalar.config.ts
export default defineConfig({
database: {
materializedViews: [
{
name: 'popular_products',
query: `
SELECT
p.id,
p.name,
p.slug,
COUNT(o.id) as order_count
FROM product p
JOIN order_item oi ON p.id = oi.product_id
JOIN order o ON oi.order_id = o.id
WHERE o.created_at > NOW() - INTERVAL '30 days'
GROUP BY p.id, p.name, p.slug
ORDER BY order_count DESC
LIMIT 100
`,
refreshInterval: '1 hour',
},
],
},
});

7. Frontend Optimization

While much of performance optimization happens on the backend, frontend techniques matter too:

State Management

Scalar’s client libraries include efficient state management:

// React example with automatic request deduplication
import { useContent } from '@scalar/react-hooks';
function ProductList({ category }) {
// Multiple components can request the same data
// without duplicate network requests
const { data, loading, error } = useContent('product', {
where: { category },
orderBy: { popularity: 'desc' },
limit: 10,
});
// Render component...
}

Predictive Prefetching

Implement predictive prefetching for common navigation paths:

import { prefetchContent } from '@scalar/client';
function ProductCard({ product }) {
const handleMouseEnter = () => {
// Prefetch full product details on hover
prefetchContent('product', {
where: { id: product.id },
include: ['related', 'reviews', 'variants']
});
};
return (
<div className="product-card" onMouseEnter={handleMouseEnter}>
{/* Product card content */}
</div>
);
}

8. Monitoring and Optimization

Continuous monitoring is essential for maintaining performance:

Real User Monitoring

Implement RUM to understand actual user experience:

scalar.config.ts
export default defineConfig({
monitoring: {
rum: {
enabled: true,
sampleRate: 0.1, // Monitor 10% of requests
excludePaths: ['/admin/**', '/api/health'],
},
},
});

Performance Dashboard

Scalar provides a built-in performance dashboard showing:

  • API response times by endpoint
  • Cache hit rates
  • Asset delivery performance
  • Database query performance
  • Error rates

Access this at /admin/performance in your Scalar admin interface.

Automated Optimization Suggestions

Scalar analyzes your usage patterns and provides automated suggestions:

// Run the performance advisor
scalar performance:analyze
// Sample output:
// ✅ Query optimization: Add index on 'blogPost.author' to improve query performance
// ✅ Cache optimization: Consider increasing cache TTL for '/api/products' to reduce database load
// ✅ Asset optimization: 3 images exceed recommended size limits

Case Study: E-commerce Performance Optimization

Let’s look at how one customer optimized their Scalar-powered e-commerce site:

Initial Challenges

  • Product listing pages loading in 3.5s (average)
  • Product detail pages loading in 2.8s
  • Cart updates taking 750ms
  • Mobile conversion rate 40% lower than desktop

Applied Optimizations

  1. Content Model Redesign

    • Normalized product variants
    • Created dedicated models for pricing and inventory
    • Implemented intelligent content references
  2. Image Pipeline

    • Implemented responsive image variants
    • Adopted WebP with JPEG fallback
    • Set up image quality tiers by importance
  3. Caching Strategy

    • Product listings: 1 hour CDN cache
    • Product details: 4 hour cache with revalidation
    • Personalized content: Edge-computed with 5-minute cache
  4. Regional Deployment

    • Deployed Scalar API to 6 edge regions
    • Implemented regional database replicas
    • Configured intelligent request routing

Results

  • Product listing pages: 950ms average load (73% improvement)
  • Product detail pages: 780ms average load (72% improvement)
  • Cart updates: 120ms (84% improvement)
  • Mobile conversion rate improved by 28%
  • 65% reduction in origin server load

Conclusion

Performance optimization is an ongoing process, not a one-time effort. Scalar provides the tools and architecture to build high-performance content experiences, but the most significant gains come from thoughtful implementation and continuous refinement.

By applying the strategies outlined in this guide, you can ensure your content delivers the speed and responsiveness users expect, regardless of scale or complexity.

For more detailed performance guidance, explore our performance documentation or reach out to our support team for personalized optimization recommendations.

Wrap-up

A CMS shouldn't slow you down. Scalar aims to expand into your workflow — whether you're coding content models, collaborating on product copy, or launching updates at 2am.

If that sounds like the kind of tooling you want to use — try Scalar or join us on Discord .