CAPTCHA-as-a-Service
High-Throughput Verification Engine & React Client SDK
Privacy-focused, distributed CAPTCHA verification architecture featuring atomic Lua validation, rate limiting, and signed JWT verification tokens.
End-to-end verification latency powered by In-Memory Redis Lua evaluation.
Single-transaction evaluate-and-delete pattern completely prevents token reuse and replay attacks.
Zero third-party tracking cookies or massive vendor scripts injected into user browsers.
Fully Dockerized container deployment with zero external vendor dependencies.
The Problem & System Scope
CAPTCHA-as-a-Service is a low-latency, privacy-centric alternative to heavy commercial CAPTCHA providers like Google reCAPTCHA and Cloudflare Turnstile. Built with Node.js, TypeScript, and Redis, it delivers millisecond-fast challenge generation, atomic server-side Lua verification that completely prevents replay attacks, cryptographically signed verification tokens, and a lightweight plug-and-play React SDK.
End-to-End Architectural Design
The system operates as an independent security microservice. The client application fetches a randomized visual challenge with distortion noise. The validation response is checked in Redis via an atomic Lua script that compares the solution and deletes the key in the exact same event-loop cycle. Successful evaluations produce a short-lived signed JWT containing verified session claims for downstream business APIs.
Challenge Generator
Generates distortion-rendered numeric challenges with visual interference lines and rotation noise.
Atomic In-Memory Engine
Single-threaded atomic verification, immediate token destruction, attempt counter decrementing.
Token Issuer
Issues short-lived cryptographically signed verification proofs for downstream consumption.
React Client SDK
Plug-and-play frontend widget with auto-refresh, audio accessibility, and customizable dark/light themes.
- STEP 1 Client component mounts and requests challenge: `GET /api/v1/captcha/generate`.
- STEP 2 Server generates 6-digit numeric sequence, applies algorithmic visual distortion noise, and stores hashed solution in Redis with 120s TTL.
- STEP 3 Client renders challenge canvas and user submits input along with challenge ID: `POST /api/v1/captcha/verify`.
- STEP 4 Redis evaluates solution atomically via Lua script: if matched, key is deleted immediately to prevent concurrent replay.
- STEP 5 If valid, server signs a JWT verification token (valid for 60s) using HMAC-SHA256 with user IP binding.
- STEP 6 Client passes the verification token in authorization header to primary business API (e.g. signup/checkout).
- STEP 7 Primary business API validates token signature using shared secret without making another database call.
Technology Choices & Justifications
Lua scripts run atomically inside Redis, guaranteeing that read-and-delete operations occur without any interleaving concurrent requests.
Strict type validation for security payloads, fast asynchronous request handling, and clean modular architecture.
Signed stateless tokens allow downstream microservices to verify CAPTCHA completion without querying the Redis database.
One-command deployment of the verification microservice and Redis cluster in any cloud environment.
Provides other developers with an effortless drop-in component: `<CaptchaWidget onVerify={setToken} />`.
Deep Technical Breakthroughs
Concurrent Replay Attacks & Race Conditions
In high-concurrency environments, an attacker could fire 50 simultaneous HTTP requests with a single solved CAPTCHA. In a standard "read from DB, then delete" architecture, multiple requests would pass before the deletion committed.
Distributed locks in Redis (Redlock) added 20-30ms latency overhead and complexity.
Executed verification inside a Redis Lua script. Because Redis executes Lua scripts on a single thread atomically, checking the solution and calling `redis.call("DEL", key)` happens with zero possibility of race condition interleaving.
Stateless Downstream Verification Without Database Coupling
When a user solves a CAPTCHA on a signup form, the main application backend must verify that the CAPTCHA was actually solved without querying the CAPTCHA database directly.
Sharing the Redis cluster across all backend microservices created tight operational coupling.
Adopted signed JWT verification tokens. Once solved, the CAPTCHA engine returns a token signed with a secret key, containing claims `{ sub: "captcha_verified", ipHash: "...", exp: now + 60s }`. The main backend only needs to verify the cryptographic signature locally in < 1ms.
Accessibility & User Friction Balance
Making challenges hard enough to block optical character recognition (OCR) bots without frustrating human users with illegible characters.
Complex distorted alphabets (mix of uppercase, lowercase, numbers) cause human frustration and high dropout rates.
Focused exclusively on high-entropy 6-digit numeric sequences paired with algorithmic line noise, slight random glyph rotation, and an optional audio synthesized fallback for visually impaired users.
Production Engineering Logic
import Redis from 'ioredis';
import { SignJWT } from 'jose';
const redis = new Redis(process.env.REDIS_URL!);
const JWT_SECRET = new TextEncoder().encode(process.env.JWT_SECRET || 'secret-key-min-32-chars');
// Atomic Lua Script: Evaluates user input against stored hash,
// deletes the key immediately on success OR decrements remaining attempts.
const ATOMIC_VERIFY_LUA = `
local key = KEYS[1]
local userInput = ARGV[1]
local storedData = redis.call('GET', key)
if not storedData then
return { 0, 'EXPIRED_OR_NOT_FOUND' }
end
local cjson = cjson.decode(storedData)
if cjson.solution == userInput then
-- Correct! Delete immediately to prevent replay
redis.call('DEL', key)
return { 1, 'VERIFIED' }
else
-- Decrement attempts remaining
cjson.attempts = cjson.attempts - 1
if cjson.attempts <= 0 then
redis.call('DEL', key)
return { -1, 'MAX_ATTEMPTS_EXCEEDED' }
else
redis.call('SET', key, cjson.encode(cjson), 'KEEPTTL')
return { 0, tostring(cjson.attempts) }
end
end
`;
export async function verifyCaptcha(challengeId: string, userInput: string, clientIp: string) {
const key = `captcha:${challengeId}`;
// Execute atomically inside Redis
const [status, message] = await redis.eval(
ATOMIC_VERIFY_LUA,
1,
key,
userInput.trim()
) as [number, string];
if (status !== 1) {
return { success: false, reason: message };
}
// Generate signed verification token valid for 60 seconds
const token = await new SignJWT({
purpose: 'captcha_verification',
challengeId,
ipHash: hashIp(clientIp),
})
.setProtectedHeader({ alg: 'HS256' })
.setIssuedAt()
.setExpirationTime('60s')
.sign(JWT_SECRET);
return {
success: true,
verificationToken: token,
expiresInSeconds: 60,
};
} Persistence & Schema Design
In-memory Redis key-value store optimized for ephemeral TTLs and sub-millisecond retrieval.
captcha:[challengeId]
Ephemeral challenge record with automatic 120-second TTL.
solution: Stringattempts: Integer (max 3)createdAt: TimestampclientIp: String
rate:ip:[clientIp]
Sliding window rate limit counter per client IP address.
count: IntegerwindowExpiresAt: Timestamp
Key Learnings & Future Enhancements
Key Engineering Learnings
- Deepened mastery of Redis Lua scripting for eliminating concurrency race conditions in microsecond environments.
- Learned how to design zero-dependency React SDKs with clean ergonomics for other software engineers.
- Discovered the architectural advantages of stateless cryptographic verification tokens (JWT) for microservice decoupling.
Future Roadmap (v2)
- Publish the React SDK as a public npm package (`@santlaj/captcha-react`).
- Add WebAssembly (Wasm) client-side proof-of-work challenges as a hybrid defense layer.
- Build a Grafana analytics dashboard tracking bot rejection rates and verification latency percentiles.