Ignore files and folders in a Runpod project
main.runpodignore file in the root of your project. This file follows standard ignore patterns similar to .gitignore.repository·main·Indexed 43 days ago
https://github.com/runpod/runpod-pythonOfficial Python library for the Runpod API and serverless worker SDK. It enables developers to manage GPU cloud resources (Pods), deploy custom AI models as scalable serverless endpoints, and interact with Runpod endpoints via REST API v2. The SDK includes tools for creating serverless workers with custom handlers, implementing fitness checks for environment validation, and utilizing VolumeCache for model hydration.
.runpodignore file in the root of your project. This file follows standard ignore patterns similar to .gitignore.RunPod can signal a worker to stop a specific job if a request is cancelled, expires, or times out. This does not affect other concurrent jobs.
If you are using async handlers that hold resources, you can perform cleanup by catching asyncio.CancelledError.
CRITICAL: You must re-raise the asyncio.CancelledError after performing cleanup. If you swallow the error, the worker will incorrectly report the job as 'completed' instead of 'stopped'.
import asyncio
async def handler(job):
try:
# Perform async work
await asyncio.sleep(10)
except asyncio.CancelledError:
# Perform cleanup
print("Cleaning up resources...")
raise # MUST re-raise to ensure job is marked as stopped
return {"output": "done"}RunPod supports multiple profiles. By default, the library uses the default profile defined in your credentials file.
In Python scripts:
You can switch the active profile by setting the runpod.profile attribute.
In CLI commands:
You can switch profiles using the --profile argument.
import runpod
runpod.profile = "my_profile"Files are stored at {volume_path}/.cache/{namespace} using a size-bucketed approach:
small.tar archive to reduce network metadata overhead.big/ subdirectory, preserving their original relative path.manifest.json file acts as the commit marker. It records file metadata (size, mtime) and is written last to ensure a complete mirror.small.tar archive is re-packed in its entirety whenever any small file changes.hydrate or sync when no changes are detected results in zero file copies.dirs before writing.The Runpod Serverless architecture is designed for high-performance I/O and reliability through several key design decisions:
aiohttp..runpod_jobs.pkl file on disk. This allows the worker to survive restarts, though it introduces a small I/O overhead (5-15ms) per job.multiprocessing.Process handles heartbeats. This ensures that even if a user handler blocks the main event loop, the worker remains visible to the Runpod API.boto3 or fastapi) are imported only when needed, reducing cold start times by 32-42%.Fitness checks allow you to validate your worker environment (e.g., checking for GPU availability or disk space) at startup. If a check fails, the worker exits with code 1, signaling the orchestrator to restart it.
Use the @runpod.serverless.register_fitness_check decorator to define checks. These run once at startup in production mode, before the handler is initialized.
import runpod
import torch
@runpod.serverless.register_fitness_check
def check_gpu_available():
if not torch.cuda.is_available():
raise RuntimeError("GPU not available")
def handler(job):
return {"output": "success"}
runpod.serverless.start({"handler": handler})To provide streaming partial results to the RunPod API, implement your handler as a generator (synchronous or asynchronous). The worker detects the generator type and uses run_job_generator to yield partial outputs.
Each yielded partial output is wrapped in the format: {"output": <partial_content>}. If an error occurs mid-stream, the worker will emit {"error": "..."}.
# Example of an async generator handler
async def my_streaming_handler(job):
yield {"output": "Part 1"}
# ... processing ...
yield {"output": "Part 2"}The Runpod serverless module is a framework designed to transform a container into a worker pod for the Runpod serverless platform. It manages the lifecycle of user-defined handler functions by polling the Runpod API for jobs, executing them, and transmitting results back to the platform.
graph TB
subgraph "Entry Point"
START[runpod.serverless.start]
end
subgraph "Worker Orchestration"
WORKER[worker.py::main]
FITNESS[run_fitness_checks]
SCALER[JobScaler]
HEARTBEAT[Heartbeat Process]
end
subgraph "Job Management"
JOBFETCH[get_jobs]
JOBRUN[run_jobs]
JOBHANDLE[handle_job]
QUEUE[asyncio.Queue]
end
subgraph "State & Logging"
STATE[JobsProgress Singleton]
LOGGER[RunPodLogger]
end
subgraph "Communication"
HTTP[HTTP Client]
RESULT[send_result]
STREAM[stream_result]
PROGRESS[progress_update]
end
subgraph "User Code"
HANDLER[User Handler Function]
end
subgraph "External Services"
RUNPOD[Runpod API]
end
START --> WORKER
WORKER --> FITNESS
FITNESS --> HEARTBEAT
FITNESS --> SCALER
SCALER --> JOBFETCH
SCALER --> JOBRUN
JOBFETCH --> QUEUE
JOBRUN --> QUEUE
JOBRUN --> JOBHANDLE
JOBHANDLE --> HANDLER
JOBHANDLE --> RESULT
JOBHANDLE --> STREAM
HANDLER --> PROGRESS
PROGRESS --> HTTP
RESULT --> HTTP
STREAM --> HTTP
HTTP --> RUNPOD
JOBFETCH --> HTTP
HEARTBEAT --> HTTP
SCALER --> STATE
JOBHANDLE --> STATE
SCALER --> LOGGER
style START fill:#1976d2,stroke:#0d47a1,stroke-width:3px,color:#fff
style FITNESS fill:#1976d2,stroke:#0d47a1,stroke-width:3px,color:#fff
style SCALER fill:#d32f2f,stroke:#b71c1c,stroke-width:3px,color:#fff
style HANDLER fill:#388e3c,stroke:#1b5e20,stroke-width:3px,color:#fff
style STATE fill:#f57c00,stroke:#e65100,stroke-width:3px,color:#fff
style RUNPOD fill:#7b1fa2,stroke:#4a148c,stroke-width:3px,color:#fffThe execution flow of a Runpod serverless worker follows a structured sequence from startup to shutdown:
runpod.serverless.start() function parses arguments and configures the worker environment.run_fitness_checks to validate worker health before accepting jobs.JobScaler component takes control, managing the acquisition of jobs from the API and orchestrating their processing.Fitness checks are validation routines that run only once at worker startup, before the first job is processed. They are designed to ensure the environment is correctly configured (e.g., GPU availability, model files, disk space) before the worker begins accepting jobs.
RuntimeError with specific details (e.g., which environment variable is missing or the exact status code received) to aid debugging.asyncio to prevent unnecessary worker exits due to temporary glitches.import runpod
@runpod.serverless.register_fitness_check
def check_first():
print("This runs first")
@runpod.serverless.register_fitness_check
def check_second():
print("This runs second")For complex operations (like downloading large files or making system changes), you can trigger a worker refresh to ensure a clean state. There are two ways to do this:
Global Refresh: Enable it during startup. This refreshes the worker after every job, regardless of success or failure.
runpod.serverless.start({"handler": handler, "refresh_worker": True})Selective Refresh: Return a refresh_worker key in your handler's return dictionary. This allows you to refresh only when specific job conditions are met.
def handler(job):
if job["input"].get("refresh", False):
return {"output": "Success", "refresh_worker": True}
return {"output": "Success"}from runpod.serverless import start
def handler(job):
return {"output": "Job completed successfully"}
start({"handler": handler, "refresh_worker": True})You can manage SSH keys for your account using the runpod ssh add-key command.
~/.runpod/ssh/.--key flag or the --key-file flag.Keys are stored locally in ~/.runpod/ssh/.
# Generate and add a new key
runpod ssh add-key
# Add an existing key via flag
runpod ssh add-key --key /path/to/id_rsa