B2B Leads API Error Codes and Troubleshooting: Handling Failures Gracefully in Production Workflows
This article equips B2B operators, agencies, and sales ops teams with a comprehensive reference for B2B Leads API error codes. It covers common HTTP status codes, JSON response error structures, rate limit handling, authentication failures, and data validation errors. The guide provides actionable troubleshooting steps, a structured retry framework, and real-world workflow patterns for maintaining reliable API integrations in production environments.

1. Introduction: Why Error Handling Matters for B2B API Workflows
In production B2B outbound operations, every API call either delivers a lead or introduces risk. Unhandled errors cascade quickly: a silent 429 Too Many Requests drops a batch of enriched contacts, a misread 400 Bad Request corrupts a CRM import, and an unmonitored 500 Internal Server Error leaves your campaign feeding stale data for hours. The difference between a resilient integration and a fragile one is how you handle those failures.
This guide covers the Dievio B2B Leads API error model from a production operator’s perspective. You’ll learn the exact structure of error responses, the meaning behind every common HTTP status code and application-level error code, and how to build a retry framework that keeps your workflows running when the API is under load. We’ll also cover authentication pitfalls, rate limit strategies, and the monitoring patterns that let you sleep through the night knowing your lead pipeline is stable.
Whether you’re integrating the API into a white-label tool, an agency delivery pipeline, or an internal RevOps stack, these patterns will help you handle failures gracefully—without losing leads, wasting credits, or burning out your ops team.
2. Understanding the B2B Leads API Error Response Structure
Every failure from the Dievio B2B Leads API comes back as a JSON object with a consistent shape. Knowing this structure lets you parse the error, log it intelligently, and decide on the next action programmatically.
<code>{
"error": {
"code": "RATE_LIMIT_EXCEEDED",
"message": "You have exceeded the rate limit. Please retry after the specified period.",
"details": {
"retry_after_seconds": 30,
"limit": 100,
"current_usage": 100
},
"request_id": "req_abc123def456"
}
}</code>Break down the fields:
code– A machine-readable string you can use in conditional logic. Examples:INVALID_API_KEY,QUOTA_EXHAUSTED,NO_RESULTS_FOUND.message– A human-readable description of the problem. Log this for debugging, but don’t display it to end users without sanitising.details– An optional object with contextual metadata. For rate limits you’ll seeretry_after_seconds; for validation errors you’ll see which parameter was invalid.request_id– A unique identifier for the failed request. Always include this when escalating to Dievio support—it lets the team trace the exact interaction.
Your integration should always log the request_id and code. This is the foundation of any production troubleshooting workflow.
3. HTTP Status Code Reference Table
| Status Code | Meaning | Category | Recommended Action |
|---|---|---|---|
400 |
Bad Request | Client Error | Inspect the details object for the invalid parameter. Fix the request and retry. |
401 |
Unauthorized | Client Error | Check your API key or OAuth token. Verify it hasn’t expired and the IP is allowed. |
403 |
Forbidden | Client Error | Your credentials are valid but lack permission for the endpoint or data scope. Review API plan. |
404 |
Not Found | Client Error | The endpoint or resource doesn’t exist. Check the URL path. This is rare with the Dievio API. |
429 |
Too Many Requests | Client Error | Rate limit reached. Use the Retry-After header or details.retry_after_seconds before retrying. |
500 |
Internal Server Error | Server Error | Transient issue. Retry with exponential backoff. If persistent, escalate with request_id. |
502 |
Bad Gateway | Server Error | Upstream infrastructure issue. Wait and retry. Avoid hammering the endpoint. |
503 |
Service Unavailable | Server Error | Temporary maintenance or overload. Retry after a delay, ideally using the Retry-After header. |
Group your retry logic by category: client errors (4xx) should generally not be retried unless they are 429 or 408 (timeout). Server errors (5xx) are always candidates for retry with backoff.
4. Common Error Codes and Their Meanings
Beyond HTTP status codes, the Dievio API returns application-level error codes in the code field. Here’s a checklist of the most frequent ones you’ll encounter in production:
INVALID_API_KEY– The API key is missing, malformed, or revoked. Frequency: Common during initial setup. Fix: Regenerate the key from the dashboard and update your environment variable.RATE_LIMIT_EXCEEDED– You’ve hit the per-second or per-minute limit. Frequency: High in burst scenarios. Fix: Pause and respect theretry_after_secondsvalue.QUOTA_EXHAUSTED– Your monthly credit allocation is consumed. Frequency: At month-end or during large campaigns. Fix: Upgrade your plan or wait for the reset. Monitor your pricing page for usage caps.INVALID_FILTER_PARAM– One of your filter values (e.g.,industry,company_size) is not recognized. Frequency: Low, but common during manual testing. Fix: Check the API documentation for allowed values and pre-validate before sending.NO_RESULTS_FOUND– The query returned zero leads. Frequency: Medium, especially with narrow filters. Fix: Broaden the criteria or use preview counts to estimate coverage before spending credits.ENRICHMENT_UNAVAILABLE– The requested enrichment (e.g., email, phone) is not available for that lead. Frequency: High for low-coverage industries. Fix: Fall back to partial data or skip the lead.TIMEOUT_ERROR– The request took longer than the allowed timeout. Frequency: Rare with standard queries. Fix: Increase your client timeout or break the request into smaller batches.
Each of these error codes maps to a specific handling strategy. We’ll dig into the most consequential ones in the sections that follow.
5. Authentication and Authorization Errors
Authentication failures are the most common cause of 401 Unauthorized and 403 Forbidden responses. Use this step-by-step checklist to resolve them:
- Check the API key format. Keys are case-sensitive. Ensure no hidden whitespace or truncation in your environment variable.
- Verify the key is active. Log into your Dievio account and regenerate the key if it was revoked or expired.
- Confirm IP allowlist rules. If your account restricts API access to specific IPs, make sure your server’s outbound IP is listed.
- Review OAuth token scopes. If you’re using OAuth, the token must include the
leads:readorleads:writescope. Refresh the token if it has expired. - Check the authorization header. The header should be exactly
Authorization: Bearer YOUR_API_KEY. Many integration errors stem from a missing “Bearer” prefix.
If you’re still seeing 401 after these steps, include the request_id in your support ticket. The Dievio engineering team can trace the exact request and identify the mismatch.
6. Rate Limit and Quota Error Handling
Rate limits protect API stability, but they can disrupt your lead generation workflows if you don’t handle them correctly. The Dievio API uses a credit-based quota system—each lead search or enrichment costs a certain number of credits. When you exceed the per-second rate or your monthly credit pool, you’ll receive a 429 Too Many Requests or QUOTA_EXHAUSTED error.
Here’s a production-ready rate limit handling framework:
- Read the response headers. The API returns
X-RateLimit-Limit,X-RateLimit-Remaining, andX-RateLimit-Reset(Unix timestamp). Use these to pace your requests proactively. - Respect the
Retry-Afterheader. When a429is returned, theRetry-Afterheader (in seconds) tells you exactly when to retry. Do not retry before that. - Implement a queue with a delay. For high-volume workflows, maintain a local queue that sends requests at a rate of 80% of the limit. This avoids hitting the ceiling entirely.
- Separate quota exhaustion from rate limits.
QUOTA_EXHAUSTEDis a permanent condition until you refill credits. Pause the workflow and alert the billing contact.
For a deeper dive on building production-safe extraction workflows, check our guide on B2B Leads API Pagination and Rate Limit Handling.
7. Building a Production Retry Framework
Not all errors are created equal. A 500 might be transient; a 400 with INVALID_FILTER_PARAM is permanent. Your retry logic must distinguish between them.
Exponential Backoff with Jitter
The standard pattern for retrying server errors is exponential backoff. Start with a small delay (e.g., 1 second), double it each retry, and add random jitter to prevent thundering herd problems. Here’s a pseudocode example:
<code>max_retries = 5
base_delay = 1 # seconds
for attempt in 1..max_retries:
response = api_call(request)
if response.status == 200:
return response.data
if response.status in [400, 401, 403, 404]:
# Permanent error – log and abort
log_error(response)
throw PermanentError(response)
if response.status == 429:
delay = response.headers['Retry-After'] || base_delay * (2 ** attempt)
sleep(delay + random_jitter(0, 0.5))
continue
if response.status >= 500:
delay = base_delay * (2 ** attempt) + random_jitter(0, 1)
sleep(delay)
continue
# After max retries – log and escalate
log_fatal_error(response)</code>Idempotency Considerations
Lead search requests are typically idempotent—retrying the same query returns the same result. But enrichment requests that consume credits are not idempotent; retrying may double-charge you. For such endpoints, use a request deduplication key (provided in the API docs) or rely on the request_id to check if the previous attempt succeeded before retrying.
For additional context, see Salesforce guide to B2B lead generation.
Circuit Breaker Pattern
If the API returns an error rate above a threshold (e.g., 50% of requests failing with 5xx), open the circuit breaker: stop sending requests for a cooldown period (e.g., 30 seconds), then try a single probe request. If it succeeds, close the circuit and resume normal operation. This prevents your retry storm from making the situation worse.
8. Data Validation and Input Errors
Most 400 Bad Request errors are preventable. The Dievio API validates filters and parameters before processing. Common validation failures include:
- Malformed company domains –
www.example.cominstead ofexample.com. - Unsupported country codes – Using
USinstead ofUSA(check the API docs for the exact format). - Invalid email patterns – Attempting enrichment with a nonexistent or malformed email string.
- Missing required fields – Omitting
first_nameorlast_namewhen the endpoint requires them.
Reduce these errors by pre-validating inputs on your side. For example, strip the www. prefix from domains, use a list of supported country codes, and ensure all required fields are populated before sending the request. A simple validation step can eliminate 80% of 400 errors.
If you’re building a white-label API integration, invest in client-side validation so your end users see clear error messages before the API call is made.
9. Timeout and Connectivity Error Patterns
Network failures happen. Your integration should handle:
- Connection timeouts – The client couldn’t establish a TCP connection within the configured time. Usually a transient network issue or DNS resolution failure.
- Read timeouts – The connection was established but the server didn’t respond within the read timeout. For large result sets, the API may need more time. Increase your read timeout to 30 seconds for batch queries.
- TLS/SSL handshake errors – Certificate validation failures. Ensure your client’s certificate store is up to date. If you’re behind a corporate proxy, adjust the TLS settings.
For read timeouts, consider using the webhook delivery patterns instead of synchronous requests. Webhooks let you submit a query and receive results asynchronously, eliminating timeout issues for large payloads.
When retrying connectivity errors, apply the same exponential backoff framework from Section 7. But set a lower max retry count (e.g., 3) because connectivity failures often indicate a broader network problem that won’t resolve quickly.
10. Monitoring and Alerting for API Errors
You can’t fix what you don’t measure. Set up monitoring for these key metrics:
- Error rate by status code – Track the percentage of 4xx and 5xx responses. A sudden spike in 5xx may indicate an API outage. A spike in 429 means you need to throttle.
- Error code frequency – Log each application error code (e.g.,
QUOTA_EXHAUSTED,NO_RESULTS_FOUND) and alert on thresholds. For example, ifNO_RESULTS_FOUNDexceeds 10% of queries, your filters may be too narrow. - Latency percentiles – High p99 latency often precedes timeout errors. Monitor your own endpoint latency as well as the API’s response time.
- Quota consumption – Track remaining credits daily. Set an alert when usage hits 80% of your monthly limit to avoid sudden workflow stoppages.
Integrate with your existing observability stack (e.g., Datadog, Sentry, or custom dashboards). The request_id is your key for correlating failures across logs, metrics, and traces.
For a proactive approach, see our forthcoming article on B2B API Monitoring and Alerting (coming soon) for detailed alerting configurations.
11. Error Handling Checklist for Production Deployments
Before you push your integration to production, run through this checklist:
- ☐ All client errors (4xx) are logged with
request_idand not retried (except 429). - ☐ Rate limit handling respects
Retry-Afterheaders and implements exponential backoff. - ☐ Server errors (5xx) are retried up to 5 times with jittered backoff, then escalated.
- ☐ Circuit breaker is configured to open after 50% error rate in a 1-minute window.
- ☐ Quota exhaustion triggers a clear alert and pauses the workflow.
- ☐ Pre-validations are in place for filters, domains, and required fields.
- ☐ Timeouts are set appropriately (connection: 10s, read: 30s for batch).
- ☐ Error responses are sanitised before being shown to end users (no raw API keys or stack traces).
- ☐ Support escalation includes the
request_idin all tickets. - ☐ Monitoring dashboards track error rates, latency, and quota usage.
This checklist is adapted from patterns used in enterprise agency automation workflows where downtime directly impacts client delivery.
12. Related Resources and Next Steps
You now have a robust framework for handling B2B Leads API errors in production. But error handling is just one piece of a resilient integration. Explore these resources to deepen your implementation:
- B2B Leads API documentation – Complete reference for endpoints, parameters, and error codes.
- API pagination patterns – Learn how to handle large result sets without triggering overflow errors.
- Webhook delivery patterns – For real-time error notification and async failure handling.
- Agency automation workflows – Production error handling patterns for multi-client delivery pipelines.
- Pricing plans – Plan your quota needs and avoid
QUOTA_EXHAUSTEDerrors.
For external best practices, the Salesforce Lead Management implementation guide offers excellent patterns for CRM integration error handling and lead validation. And the HubSpot guide to sales prospecting provides context for aligning your API error handling with broader sales ops workflows.
If you encounter an error that our troubleshooting docs don’t cover, include the request_id and reach out to Dievio support. We’re here to keep your lead pipeline flowing.
Related workflow: B2B Leads API Pagination: How to Pull Large Lead Lists Safely.
Related workflow: B2B Leads API Webhook Integration: Real-Time Lead Delivery for Automated Outbound Triggers.
Build Your First Outbound List to validate the segment before you commit to full outreach.


