Error Handling and Reliability

HTTP status codes, error response format, retry guidance, timeouts, and idempotency patterns for mCards API integrations.

Error Handling and Reliability

This guide covers error handling patterns, HTTP status codes, retry strategies, and reliability best practices that apply across all mCards APIs.


HTTP Status Codes

Success Codes

CodeMeaningWhen Returned
200 OKRequest succeededGET, PUT, PATCH requests
201 CreatedResource createdPOST requests that create a new resource
204 No ContentRequest succeeded, no bodyDELETE requests

Client Error Codes

CodeMeaningAction
400 Bad RequestMalformed request or invalid parametersFix the request body or parameters and retry
401 UnauthorizedInvalid or missing authenticationVerify your API key, secret, and HMAC signature
403 ForbiddenValid credentials but insufficient permissionsCheck your partner role assignments
404 Not FoundResource does not exist or is not in your scopeVerify the resource UUID and your data scope
422 Unprocessable EntityRequest is well-formed but semantically invalidReview the error details for validation failures
429 Too Many RequestsRate limit exceededBack off and retry after the indicated period

Server Error Codes

CodeMeaningAction
500 Internal Server ErrorUnexpected server failureRetry with exponential backoff
502 Bad GatewayUpstream service unavailableRetry with exponential backoff
503 Service UnavailableServer temporarily overloadedRetry with exponential backoff
504 Gateway TimeoutRequest timed outRetry with exponential backoff

Error Response Format

Error responses include a JSON body with details about what went wrong:

{
  "errors": [
    {
      "detail": "Description of the error",
      "source": {
        "pointer": "/data/attributes/field_name"
      }
    }
  ]
}

Use the detail field for debugging and the source pointer (when present) to identify which field caused the error.


Retry Strategy

When to Retry

ScenarioRetry?Strategy
5xx server errorsYesExponential backoff with jitter
429 rate limitYesWait for the indicated retry period
408 request timeoutYesRetry immediately, then backoff
4xx client errors (except 429)NoFix the request before retrying
Network timeout / connection refusedYesExponential backoff with jitter

Exponential Backoff

For retryable errors, use exponential backoff with jitter:

wait_time = min(base_delay * 2^attempt + random_jitter, max_delay)

Recommended values:

  • Base delay: 1 second
  • Max delay: 60 seconds
  • Max retries: 5 attempts
  • Jitter: Random value between 0 and 1 second

Example (Python)

import time
import random

def retry_with_backoff(request_func, max_retries=5):
    for attempt in range(max_retries):
        response = request_func()
        if response.status_code < 500 and response.status_code != 429 and response.status_code != 408:
            return response

        wait = min(1 * (2 ** attempt) + random.uniform(0, 1), 60)
        time.sleep(wait)

    raise Exception("Max retries exceeded")

Timeouts

API Request Timeouts

Set appropriate timeouts for API calls:

Timeout TypeRecommended Value
Connection timeout10 seconds
Read timeout30 seconds

Webhook Response Timeouts

For partners responding to payment authorization webhooks (payment.* events):

  • mCards expects a response within a defined timeout window
  • The cardholder is waiting at the point of sale — respond as quickly as possible
  • If your service cannot respond in time, the DPE moves to the next payment account in rank order

Idempotency

Design your integration to handle duplicate requests gracefully:

  • Webhook handlers — The same event may be delivered more than once. Use the event payload to deduplicate (e.g., by transaction ID or event ID)
  • API writes — If a request times out and you are unsure whether it succeeded, it is safe to retry POST requests that create resources — duplicate creation attempts will return an appropriate error rather than creating duplicates

Best Practices

  1. Log request and response details — Include the HTTP status code, response body, and request ID for debugging
  2. Monitor error rates — Track 4xx and 5xx rates to detect integration issues early
  3. Handle partial failures — When processing batches, handle individual item failures without aborting the entire batch
  4. Use circuit breakers — If errors persist, temporarily stop sending requests to avoid cascading failures
  5. Test in sandbox — Validate error handling in the sandbox environment before going to production

Related Guides