Intermediate
How to optimize function memory and duration on Vercel
Quick Answer
Optimize Vercel functions by configuring memory allocation in vercel.json, implementing efficient code patterns, and monitoring execution metrics. Use proper caching strategies and minimize cold starts to reduce duration and memory usage.
Prerequisites
- Active Vercel account
- Deployed project with serverless functions
- Access to project settings
- Basic understanding of serverless architecture
1
Configure function memory limits in vercel.json
Create or update your
Set memory values between 128MB and 3008MB based on your function's requirements.
vercel.json file in the project root. Add memory configuration for specific functions:{
"functions": {
"api/heavy-function.js": {
"memory": 1024
},
"api/light-function.js": {
"memory": 128
}
}
}Set memory values between 128MB and 3008MB based on your function's requirements.
Tip
Start with lower memory values and increase only if you encounter out-of-memory errors
2
Set maximum execution duration
Configure the
Duration is set in seconds. Free plans are limited to 10 seconds, Pro plans up to 60 seconds, and Enterprise up to 900 seconds.
maxDuration property in your vercel.json to prevent functions from running indefinitely:{
"functions": {
"api/*.js": {
"maxDuration": 10
}
}
}Duration is set in seconds. Free plans are limited to 10 seconds, Pro plans up to 60 seconds, and Enterprise up to 900 seconds.
Tip
Set realistic timeouts based on your function's actual needs to avoid unnecessary costs
3
Optimize code for memory efficiency
Implement memory-efficient coding practices:
- Use
constandletinstead ofvarfor proper garbage collection - Avoid loading large dependencies unnecessarily
- Process data in chunks rather than loading everything into memory
- Use streaming for large file operations
- Clear variables when done:
largeObject = null
Tip
Use dynamic imports to load dependencies only when needed
4
Implement connection pooling and caching
Reuse database connections and cache frequently accessed data:
Use external caching services like Redis or Vercel's Edge Config for shared state.
// Global connection variable
let cachedConnection = null;
export default async function handler(req, res) {
if (!cachedConnection) {
cachedConnection = await createConnection();
}
// Use cached connection
}Use external caching services like Redis or Vercel's Edge Config for shared state.
Tip
Cache database connections outside the handler function to reuse them across invocations
5
Monitor function performance
Access the Functions tab in your Vercel dashboard to monitor:
Click on individual function invocations to see detailed metrics and logs. Use this data to identify optimization opportunities.
- Memory usage patterns
- Execution duration
- Cold start frequency
- Error rates and timeouts
Click on individual function invocations to see detailed metrics and logs. Use this data to identify optimization opportunities.
Tip
Set up alerts for functions that consistently approach memory or duration limits
6
Minimize cold start impact
Reduce cold start penalties by:
- Keeping function code lightweight
- Using Vercel's Edge Functions for simple operations
- Implementing connection warming strategies
- Avoiding heavy initialization code
- Using
importstatements at the top level only for critical dependencies
Tip
Consider using Vercel's Cron Jobs to keep functions warm during peak usage periods
7
Deploy and test optimizations
Deploy your optimized functions using
vercel --prod or through Git integration. Test performance improvements by:- Running load tests on optimized endpoints
- Comparing before/after metrics in the dashboard
- Monitoring memory usage under different loads
- Verifying execution times meet requirements
Tip
Use staging environments to test optimizations before deploying to production
Troubleshooting
Function exceeds memory limit and crashes
Increase memory allocation in
vercel.json or optimize code to use less memory. Check for memory leaks and ensure large objects are properly disposed of.Function times out before completion
Increase
maxDuration in vercel.json or optimize code performance. Consider breaking large operations into smaller chunks or using background jobs for heavy processing.High memory usage despite optimization
Profile your function using
console.log(process.memoryUsage()) to identify memory hotspots. Check for circular references and ensure proper cleanup of event listeners and timers.Configuration changes not taking effect
Ensure
vercel.json is in the project root and properly formatted. Redeploy the project completely using vercel --prod --force to apply configuration changes.Ready to get started with Vercel?
Put this tutorial into practice. Visit Vercel and follow the steps above.
Visit Vercel →