Named Credentials Patterns
Overview
Named Credentials should be the default integration boundary for outbound callouts from Salesforce.
They separate endpoint/auth configuration from Apex logic, reduce secret sprawl, and make environment promotion safer.
Consensus Best Practices
- Never hardcode endpoint URLs or tokens in Apex.
- Use one Named Credential per logical external service and environment.
- Keep service-specific path/query logic in code, but base URL/auth in Named Credentials.
- Use dedicated integration users with least privilege.
- Standardize timeout/retry/error handling around all callouts.
Core Patterns
Pattern 1: Service Class + Named Credential Endpoint
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:BillingApi/v1/invoices');
req.setMethod('GET');
req.setTimeout(120000);
HttpResponse res = new Http().send(req);
Use a service layer (BillingApiService) to centralize parsing and error contracts.
Pattern 2: Environment Isolation
BillingApi_DEVBillingApi_UATBillingApi_PROD
Avoid environment if/else statements in Apex. Route environment differences through deployment metadata/config.
Pattern 3: Metadata-Driven Endpoint Selection
Store logical interface keys in Custom Metadata and resolve to Named Credential names at runtime only when necessary.
Use this for multi-tenant or multi-endpoint integration landscapes.
Security and Governance
- Restrict who can modify external credentials and named credentials.
- Review connected app and token usage regularly.
- Keep integration ownership explicit (owner team, purpose, SLA, data classification).
Operational Checklist
- Named Credential exists for each integration environment.
- Service layer references
callout:endpoints only. - Timeouts are explicit and documented.
- Retry behavior defined for transient failures.
- Correlation IDs logged for cross-system tracing.
- Failure runbook documented (revoke/rotate/recover).
Common Failure Modes
- Hardcoded hostnames in legacy Apex classes.
- Mixed auth styles across services.
- Hidden environment routing in code branches.
- No monitoring on repeated 401/403/429 responses.