Documentation
Best Practices

Corridorly Best Practices

Essential guidelines for building robust, secure, and production-ready integrations with Corridorly. Follow these practices to optimise performance, security, and reliability.

SecurityPerformanceReliability

Overview

This guide consolidates best practices from across the Corridorly platform. Whether you're implementing the smart router, handling webhooks, or preparing for production, these guidelines will help you build a robust integration.

Security First

Protect API keys, verify webhooks, use HTTPS, and follow least privilege access

Optimised Performance

Minimise payload sizes, implement caching, and monitor execution times

Production Ready

Test thoroughly, monitor actively, and prepare for edge cases


API Usage Best Practices

Follow these patterns when making API requests to ensure reliability and predictability.

Always Use Idempotency KeysCritical

Include a unique idempotency_key in every payment request to prevent duplicate charges if a request is retried.

Good Practice
{
  "amount": 9900,
  "currency": "GBP",
  "idempotency_key": "payment_${timestamp}_${customerId}_${orderId}"
}
Recommended format: Include timestamp, customer ID, and order ID to ensure uniqueness across retry attempts

Use Test Mode During Development

Set testMode: true in metadata to prevent real charges and external API calls.

{
  "amount": 9900,
  "currency": "GBP",
  "metadata": {
    "testMode": true,  // Prevents real charges
    "orderId": "test_order_123"
  }
}
Important: Always use development API keys (starting with sk_dev_) when testing, never production keys

Minimise Payload Size

Only include necessary data in API requests. Large payloads increase latency and processing time.

Avoid
  • • Sending entire user objects
  • • Including unnecessary metadata
  • • Duplicating data already stored
Prefer
  • • Send only customer ID
  • • Include essential fields only
  • • Reference existing records

Set Appropriate HTTP Headers

Always include proper headers for authentication and content type.

Content-Type: application/json
Authorization: Bearer sk_dev_your_secret_key
X-Tenant-ID: your_tenant_id
// Optional: for request tracking
X-Request-ID: unique_request_identifier

Security Best Practices

Security is paramount when handling payment data. Follow these practices to protect your integration and customer data.

Protect API KeysCritical

API keys provide full access to your Corridorly account. Treat them like passwords.

Store in environment variables, never hardcode in source
Use secret management systems (AWS Secrets Manager, HashiCorp Vault)
Never commit to version control (.env files in .gitignore)
Rotate keys regularly (every 90 days minimum)
Use separate keys for dev, staging, and production
Revoke immediately if compromised

Always Verify Webhook SignaturesCritical

Never trust webhook payloads without HMAC-SHA256 signature verification. This prevents spoofing attacks.

Node.js Example
const crypto = require('crypto');

function verifyWebhook(payload, signature, secret) {
  const hmac = crypto
    .createHmac('sha256', secret)
    .update(JSON.stringify(payload))
    .digest('hex');

  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(hmac)
  );
}

// In webhook handler
const signature = req.headers['x-corridorly-signature'];
if (!verifyWebhook(req.body, signature, webhookSecret)) {
  return res.status(401).send('Invalid signature');
}

Use HTTPS Everywhere

All webhook endpoints must use HTTPS with valid TLS certificates. Self-signed certificates will fail.

Accepted
https://api.yourapp.com/webhooks
Rejected
http://api.yourapp.com/webhooks

Principle of Least Privilege

Grant team members only the permissions they need. Regularly audit access.

Admin:Full access—only for founders/CTO
Developer:API keys, settings—for engineering team
Viewer:Read-only access—for support, finance

Webhook Implementation

Webhooks enable real-time event processing. Follow these practices for reliable webhook handling.

Respond Quickly (Within 10-15 Seconds)

Return a 200 OK response immediately. Process events asynchronously in background jobs.

Good Pattern
app.post('/webhook', (req, res) => {
  // Verify signature
  verifySignature(req);

  // Queue for processing
  queue.add(req.body);

  // Immediate response
  res.status(200).send('OK');
});
Bad Pattern
app.post('/webhook', async (req, res) => {
  // Process synchronously (SLOW!)
  await updateDatabase(req.body);
  await sendEmail(req.body);
  await updateCache(req.body);

  res.status(200).send('OK');
});
Timeout limits: Standard tier = 10s, Premium tier = 15s

Implement Webhook Idempotency

Store processed event IDs to skip duplicates. Webhooks may be sent multiple times.

const processedEvents = new Set(); // or database

app.post('/webhook', async (req, res) => {
  const eventId = req.body.id;

  // Check if already processed
  if (processedEvents.has(eventId)) {
    return res.status(200).send('Already processed');
  }

  // Process event
  await queue.add(req.body);

  // Mark as processed
  processedEvents.add(eventId);

  res.status(200).send('OK');
});

Monitor Webhook Health

Track delivery success rates and set up alerts for failed deliveries.

Monitor in Dashboard:
  • • Delivery success rate
  • • Failed delivery logs
  • • Average response times
  • • Retry attempt counts
Set Alerts For:
  • • Success rate drops below 95%
  • • 5+ consecutive failures
  • • Response time exceeds 8 seconds
  • • SSL certificate expiring soon

Payment Routing Optimization

Optimise how the smart router selects payment providers to maximise success rates and minimise costs.

Configure Provider Priorities

Set up multiple payment providers with appropriate priorities for different scenarios.

Geographic Coverage:
  • • Europe: Stripe, Adyen
  • • APAC: Adyen, local providers
  • • LATAM: Local providers first
  • • US/CA: Stripe primary
Cost Optimization:
  • • Domestic: Lower-cost providers
  • • Cross-border: Specialists
  • • High volume: Negotiate rates
  • • Enterprise: Custom routing

Monitor Provider Performance

Review routing decisions and success rates regularly to identify optimisation opportunities.

Track success rates by provider, region, and currency
Review routing_decision.factors in API responses
Monitor provider health scores over time
Identify patterns in declined transactions

Plan for Provider Failures

Configure backup providers and understand the automatic fallback behavior.

Automatic Fallback: The smart router will attempt backup providers if the primary provider fails or is unhealthy. Ensure you have at least 2-3 providers configured for critical currencies.

Error Handling

Robust error handling ensures your integration gracefully handles failures and provides clear feedback.

Implement Client-Side Retry Logic

The Corridorly API does not automatically retry failed requests. Implement exponential backoff for transient errors.

Example Retry Strategy
async function makePaymentWithRetry(paymentData, maxRetries = 3) {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      const response = await corridorly.payments.route(paymentData);
      return response; // Success

    } catch (error) {
      // Retry on transient errors (500, 503, network issues)
      if (isRetryable(error) && attempt < maxRetries - 1) {
        const delay = Math.pow(2, attempt) * 1000; // Exponential backoff
        await sleep(delay);
        continue;
      }
      throw error; // Non-retryable or max attempts reached
    }
  }
}

function isRetryable(error) {
  return error.status >= 500 || error.code === 'NETWORK_ERROR';
}

Handle Error Codes Appropriately

Different errors require different handling strategies.

400 Bad Request• Don't retry

Invalid request data. Fix the payload and resubmit.

401 Unauthorized• Don't retry

Invalid API key. Check authentication credentials.

422 Unprocessable• Don't retry

Missing required fields or validation failed. Review error message.

500/503 Server Error✓ Safe to retry

Temporary issue. Retry with exponential backoff.

Log Errors Comprehensively

Capture sufficient context to debug issues quickly.

Request ID (from X-Request-ID header)
Idempotency key used
Payment/transaction ID if available
Full error message and stack trace
Timestamp and user/customer context
Security Note: Never log full API keys or sensitive payment details (card numbers, CVV). Redact or hash before logging.

Testing & Development

Thorough testing ensures your integration works reliably before going to production.

Use Test Mode Extensively

Test mode prevents real charges and external API calls. Use it for all development and testing.

Test Mode Enables:
  • • Simulated payment processing
  • • No real provider API calls
  • • Predictable test scenarios
  • • Safe experimentation
Test Scenarios:
  • • Successful payments
  • • Declined transactions
  • • Network timeouts
  • • Provider failures

Test Webhooks Locally

Use tools like ngrok or webhook.site to test webhooks during development.

Using ngrok
# 1. Start your local server
npm run dev

# 2. Expose via ngrok
ngrok http 3000

# 3. Use the ngrok URL in Corridorly dashboard
https://abc123.ngrok.io/api/webhooks

# 4. Test events fire to your local machine
Alternative: Use webhook.site to inspect webhook payloads without writing code

Test Critical User Flows

Create integration tests for your main payment scenarios.

Successful payment with optimal routing
Soft decline recovery (retry with same card)
Hard decline handling (expired card, etc.)
Webhook receipt and processing
Idempotency key behavior
Multi-currency transactions

Production Readiness Checklist

Ensure you've completed all critical steps before going live with Corridorly in production.

Security Checklist

Configuration Checklist

Code Quality Checklist

Monitoring Checklist


Monitoring & Observability

Continuous monitoring helps you identify issues quickly and maintain high availability.

Track Key Metrics

Monitor these critical metrics in your dashboard and analytics tools.

Payment Metrics:
  • • Success rate (target: ≥95%)
  • • Average transaction amount
  • • Decline rate by reason
  • • Provider distribution
  • • Geographic breakdown
System Metrics:
  • • API response times
  • • Webhook delivery success rate
  • • Error rates by type
  • • Retry attempt frequency
  • • Provider health scores

Configure Critical Alerts

Set up alerts for conditions that require immediate attention.

Critical (P0):Payment success rate drops below 90%, all providers failing
High (P1):Webhook delivery failure rate above 10%, provider down
Medium (P2):Success rate drops below 95%, response time increase

Review Dashboard Regularly

Make dashboard reviews part of your routine operations.

Daily
  • • Transaction volume
  • • Success rates
  • • Recent errors
Weekly
  • • Provider performance
  • • Geographic trends
  • • Webhook health
Monthly
  • • Cost analysis
  • • Routing optimization
  • • Access review

Ready to Build?

With these best practices in place, you're ready to build a robust, production-ready integration with Corridorly.