TimeoutError
modal.exception.TimeoutError
Stack trace
modal.exception.TimeoutError: Function execution exceeded max runtime limit and was terminated.
Why it happens
Modal enforces a maximum execution time for functions to prevent runaway processes and resource exhaustion. When a function runs longer than this configured timeout, Modal forcibly stops it and raises a TimeoutError. This often happens with long-running or blocking code without proper async handling or time limits.
Detection
Monitor function execution durations via Modal logs or metrics, and catch modal.exception.TimeoutError exceptions to detect when timeouts occur before full failure.
Causes & fixes
Function logic takes longer than the configured max execution time.
Optimize the function code to run faster or split the workload into smaller tasks that complete within the timeout.
Blocking calls or infinite loops prevent timely completion.
Add timeouts or async handling to blocking operations and ensure loops have proper exit conditions.
Modal function max execution time is set too low for the workload.
Increase the max execution time setting in the Modal function configuration to allow longer runtimes.
Code: broken vs fixed
import modal
@modal.function(timeout=30) # 30 seconds max execution time
async def long_task():
while True:
pass # Infinite loop causes timeout
long_task.call() # This line triggers TimeoutError import os
import modal
@modal.function(timeout=300) # Increased timeout to 5 minutes
async def long_task():
# Example: simulate work with async sleep instead of infinite loop
import asyncio
for _ in range(10):
await asyncio.sleep(10) # Non-blocking sleep
if __name__ == "__main__":
long_task.call() # Fixed: longer timeout and no infinite loop Workaround
Wrap the function logic in try/except modal.exception.TimeoutError to catch timeouts and implement retry or partial progress saving.
Prevention
Design Modal functions with appropriate timeouts, avoid blocking or infinite loops, and break long tasks into smaller chunks to stay within execution limits.