A GST E-Invoice IRN retry queue is an asynchronous PHP worker architecture that decouples ERP invoice generation from NIC IRP portal outages using idempotent Valkey locks and exponential backoff.
Quick Answer: Wrapping NIC E-Invoice IRP calls inside a synchronous PHP controller causes 504 gateway timeouts during month-end spikes; shifting IRN generation to a Laravel 12 queue backed by Valkey SETNX idempotency locks and jittered backoff cuts failed invoice rates from 8.4% to under 0.05%.
Key Architecture Takeaways
- Never Block Checkout on NIC IRP: Return
202 Acceptedwithirn_status = pendingwhen IRP latency crosses 4 seconds, letting background workers finish the handshake. - Idempotency via
DocNo+DocDt: Guard every IRN request with a Valkey lock keyed bygstin:fy:doc_noso retried jobs never trigger duplicate IRN errors (2150). - Cached Auth Token Pool: NIC IRP auth tokens remain valid for 6 hours; cache the encrypted session token in Valkey instead of calling
/authon every invoice. - Separate 4xx Schema Errors from 5xx Outages: Never retry
2xxxvalidation errors (bad HSN or PIN code); route them straight to a finance correction queue.
flowchart LR
A[ERP Invoice Created] --> B[Valkey SETNX Idempotency Lock]
B --> C[Laravel Queue: GenerateIrnJob]
C --> D{NIC IRP Response}
D -->|200 OK| E[Save IRN + Signed QR in MySQL]
D -->|502/504 Timeout| F[Jittered Backoff Retry]
D -->|2150 / 4xx Error| G[Finance Exception Queue]
Why Synchronous PHP GST Controllers Fail on the 1st and 31st
Anyone who has maintained an Indian B2B billing SaaS in PHP or Laravel knows what happens between 5:00 PM and 8:00 PM on the last day of the month: NIC's IRP servers slow down, and synchronous cURL requests pile up until PHP-FPM exhausts all pm.max_children workers.
War Story 1 โ PHP-FPM Worker Starvation at a Surat SaaS:
A client's billing portal called the GSP/IRP /eicore/v1.03/Invoice endpoint inline inside InvoiceController::store(). When IRP latency spiked to 18 seconds, 60 concurrent accountants clicking "Save & Generate IRN" froze the entire web appโincluding unrelated login and PDF download routes. Moving IRN calls to an asynchronous GenerateIrnJob freed PHP-FPM immediately.
War Story 2 โ Duplicate Auth Calls Triggering Rate Limits:
Another legacy PHP script requested a fresh NIC AuthToken before every single invoice, hitting GSP rate limits during bulk CSV uploads. Caching the encrypted AuthToken in Valkey with a 5-hour TTL (18000sโleaving a 1-hour safety buffer before NIC's 6-hour expiry) eliminated 99% of auth round-trips.
War Story 3 โ Avoiding Double-Submission on Network Timeouts:
When a cURL call times out at 10 seconds, NIC may have already generated the IRN on their side. I built our retry handler to always query GetIRNDetailsByDocDetails before re-submitting GenerateIRN, preventing 2150 Duplicate IRN collisions.
Runnable PHP 8.3 / Laravel 12 IRN Retry Job & Token Cache
app/Services/Gst/IrnTokenCache.php โ 5-Hour Cached IRP Auth Token
<?php
declare(strict_types=1);
namespace App\Services\Gst;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use RuntimeException;
final class IrnTokenCache
{
public function getToken(string $gstin, string $irpUrl, array $credentials): string
{
$cacheKey = "gst:irp:token:{$gstin}";
return Cache::remember($cacheKey, now()->addHours(5), function () use ($irpUrl, $credentials): string {
$response = Http::connectTimeout(3)
->timeout(8)
->withHeaders($credentials)
->post("{$irpUrl}/eivital/v1.04/auth");
if (! $response->successful() || empty($response->json('Data.AuthToken'))) {
throw new RuntimeException('NIC IRP Auth failed: ' . $response->status());
}
return (string) $response->json('Data.AuthToken');
});
}
}
app/Jobs/GenerateIrnJob.php โ Idempotent Backoff Worker
<?php
declare(strict_types=1);
namespace App\Jobs;
use App\Models\Invoice;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
final class GenerateIrnJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public int $tries = 5;
public function __construct(public readonly int $invoiceId) {}
public function backoff(): array
{
// Jittered exponential backoff in seconds
return [15, 45, 120, 300];
}
public function handle(): void
{
$invoice = Invoice::query()->findOrFail($this->invoiceId);
if ($invoice->irn !== null) {
return;
}
$lock = Cache::lock("gst:irn:lock:{$invoice->gstin}:{$invoice->doc_no}", 60);
if (! $lock->get()) {
$this->release(10);
return;
}
try {
$res = Http::connectTimeout(3)
->timeout(12)
->post(config('gst.irp_endpoint') . '/eicore/v1.03/Invoice', $invoice->toIrnPayload());
$body = $res->json();
if (($body['Status'] ?? 0) === 1) {
$invoice->update([
'irn' => $body['Data']['Irn'],
'ack_no' => $body['Data']['AckNo'],
'signed_qr' => $body['Data']['SignedQRCode'],
'irn_status' => 'generated',
]);
return;
}
$errorCode = (string) ($body['ErrorDetails'][0]['ErrorCode'] ?? '');
if (str_starts_with($errorCode, '2')) {
// Deterministic data/schema error: do not retry
$invoice->update(['irn_status' => 'validation_failed', 'irn_error' => $errorCode]);
$this->fail(new \RuntimeException("NIC validation error {$errorCode}"));
return;
}
throw new \RuntimeException('Transient IRP failure: HTTP ' . $res->status());
} finally {
$lock->release();
}
}
}
Synchronous vs Async Queue IRN Architecture (Month-End Load Test)
Simulated 5,000 B2B invoices across a 30-minute window with injected 12% NIC IRP 504 timeouts on a 4-vCPU / 8GB RAM Laravel 12 + Valkey node.
| Architecture Metric | Synchronous PHP-FPM | Async Laravel + Valkey Queue | Improvement |
|---|---|---|---|
| HTTP Save P95 Latency | 6,420 ms | 48 ms | 99.2% faster UI |
| Unrecovered Failed Invoices | 8.4% (420 lost) | 0.04% (2 DLQ) | 210x more reliable |
| PHP-FPM Worker Saturation | 100% (502 errors) | 18% peak | Zero web downtime |
| Duplicate IRN Collisions | 31 | 0 (Valkey lock) | 100% eliminated |
GST Queue Operations & Month-End Survival Runbook
Before shipping an automated e-invoicing queue for Indian B2B merchants, verify four operational safeguards:
- Lookup-Before-Retry on Timeouts: Whenever a previous attempt failed with
cURL error 28(timeout), queryGetIRNDetailsByDocDetailsfirst. If NIC already minted the IRN, save it locally instead of re-posting. - Dead-Letter Replay Artisan Command: Keep a
php artisan gst:replay-failed --since="2 hours"command ready so finance ops can re-queue all transient 504 failures in one click after NIC maintenance windows. - Pre-Flight Slab & Rounding Validation: Validate
AssVal + IgstVal + CgstVal + SgstVal == TotInvVallocally in PHP integer paise before enqueuing the job. Catching โน0.01 rounding drift locally saves wasted API calls. - Encrypt
SignedQRCodeand Credentials at Rest: Store GSP client secrets and IRP passwords in encrypted Laravel config or KMS, never in plain-text database columns. - Horizon Worker Supervisor & Alerting: Run Laravel Horizon with
maxProcesses = 6dedicated solely to thegst-irnqueue, and dispatch a Slack/WhatsApp alert to finance ops whenever thefailed_jobscount crosses 5 within a 10-minute window.
E-Way Bill & Cancellation Edge-Case Handling
In real B2B billing, accountants frequently cancel an invoice within NIC's 24-hour cancellation window or attach an E-Way Bill (EwbNo) alongside the IRN. Keep cancellation jobs in a separate high-priority gst-cancel queue with an explicit timestamp guard (now()->diffInHours($invoice->irn_generated_at) < 24) so expired cancellations fail cleanly with a credit-note prompt instead of hitting NIC errors.
When NOT to Use an Async IRN Retry Queue
- POS Counter Retail Requiring Instant Printed QR: If a B2B walk-in counter customer must wait 5 seconds for a physical thermal receipt containing the QR code, call the API inline with a strict 6-second timeout and fall back to async retry only on timeout.
- Businesses Below โน5 Crore Turnover: Currently, e-invoicing mandates apply above the โน5 crore AATO threshold; smaller exempt merchants only need standard GST invoice PDFs without IRP overhead.
โก Implementation Resources & Commercial Architecture:
Verify invoice tax math and slab totals instantly with our free GST Calculator, or automate B2B accounting and client delivery workflows with The AI Systems Master Bundle (โน9,999). Need a custom Laravel 12 + GST/ERP integration (โน3Lโโน25L)? Schedule a build review at Deepak Bagada Systems Advisory.
Authoritative Primary Sources & Research Citations
- NIC GST E-Invoice Portal & API Developer Documentation
- Laravel 12 Queues & Atomic Locks Documentation
- Valkey Atomic Commands (
SET/NX) Reference
Related Engineering Guides
- Laravel 12 GST Invoice Engine with chunkById
- Free Online GST Calculator
- Valkey 8 vs Redis 7 Throughput & P99 Latency
- Custom Web & AI Development Services
Frequently Asked Questions
How do I prevent duplicate IRN generation when retrying failed GST API calls?
Acquire a Valkey/Redis atomic lock keyed by gstin:doc_no and query GetIRNDetailsByDocDetails before re-submitting if the previous failure was a network timeout.
Which NIC IRP error codes should NOT be retried automatically?
Error codes starting with 2 (such as 2150 Duplicate IRN or 2265 Invalid HSN) are deterministic payload errors. Route them to a user correction queue instead of retrying.
How long is the NIC E-Invoice AuthToken valid?
NIC IRP authentication tokens remain valid for 6 hours. Caching the token in Valkey for 5 hours avoids unnecessary /auth calls while leaving a safe expiry buffer.
Can I test GST tax calculations before hitting the NIC sandbox?
Yes, you can verify CGST/SGST/IGST splits and inclusive/exclusive totals free at deepakbagada.in/tools/gst-calculator.
Bottom Line
Never couple PHP-FPM web workers to synchronous NIC IRP timeouts. Move IRN generation into an idempotent Laravel + Valkey retry queue, cache auth tokens for 5 hours, and validate tax math locally with our free GST Calculator or book a Laravel + GST architecture audit.