Engineering OTP Auth for Intermittent Connectivity in Agri-tech
Knowledge Hub
Technology

Engineering OTP Auth for Intermittent Connectivity in Agri-tech

Last month, while testing our latest marketplace features near a mandi in rural Madhya Pradesh, I watched a farmer try to log into our app. He had two bars of...

KhetiSetu Agronomy Research Team
Nov 22, 2026
6 min read
9,164 views

Share this guide

Help more farmers discover useful tools

Save Time

Instant access

More Benefits

Apply for schemes

Better Decisions

Real-time data

Transparent & Safe

Official platforms

Last month, while testing our latest marketplace features near a mandi in rural Madhya Pradesh, I watched a farmer try to log into our app. He had two bars of "E" (Edge) connectivity. He entered his phone number, waited ten seconds, and when the SMS didn't arrive instantly, he tapped "Resend OTP" four times in quick succession.

By the time the first SMS arrived, he had already triggered a rate-limit block on our backend. Even worse, when the subsequent three SMS codes finally hit his phone, he didn't know which one was the "active" one. He was locked out of the system before he could even list his soy harvest.

In the comfortable bubble of high-speed office Wi-Fi, we often design authentication flows that assume a round-trip time of milliseconds. But at KhetiSetu, we’ve had to rethink OTP (One-Time Password) architecture to handle the reality of the Indian countryside: high latency, intermittent packet loss, and varying levels of digital literacy.

The "Resend" Storm: Why Standard Rate Limiting Fails

Most tutorials suggest a simple fixed-window rate limit: "Allow 3 requests every 60 seconds." In a rural setting, this is a recipe for a support nightmare. If an SMS gateway is congested (a common occurrence with Indian carriers), the message might take 45 seconds to arrive. A frustrated user will hit "Resend" long before that.

If we use a strict fixed window, we block a legitimate user who is just being impatient because the network is failing them. If we have no limit, we get hit with massive SMS API bills from bot attacks.

We solved this by implementing a Sliding Window Log with Exponential Backoff on the client-side, paired with a Redis-backed state machine on the server.

The Logic Flow

Instead of just blocking the user, we change the UI state based on the probability of delivery.

sequenceDiagram
    participant User
    participant App as Next.js Frontend
    participant API as Auth Service (Node/Redis)
    participant SMS as SMS Gateway (DLT)

    User->>App: Enter Mobile Number
    App->>API: POST /api/auth/send-otp
    API->>SMS: Trigger SMS
    SMS-->>User: (Delayed due to 2G)
    Note over User,App: Timer starts (60s)
    User->>App: Taps "Resend" (at 15s)
    App->>App: UI Blocked (Wait for timer)
    Note over User,App: Timer expires
    User->>App: Taps "Resend"
    App->>API: POST /api/auth/send-otp (Attempt 2)
    API->>API: Increment Redis Counter (TTL 15m)
    API->>SMS: Trigger SMS
    SMS-->>User: SMS 1 Arrives
    SMS-->>User: SMS 2 Arrives

Implementing Adaptive Rate-Limiting in Next.js

Using Next.js for our marketplace frontend allows us to handle some of this logic via API routes, but the heavy lifting happens in Redis. We don't just track how many OTPs were sent; we track the intent.

Here is a simplified version of the rate-limiting middleware we use to protect our endpoints while remaining "farmer-friendly."

// lib/rate-limit.ts
import redis from './redis';

export async function checkOtpLimit(phoneNumber: string) {
  const key = `otp_limit:${phoneNumber}`;
  const attempts = await redis.incr(key);

  if (attempts === 1) {
    await redis.expire(key, 900); // 15-minute window
  }

  // Adaptive cooling: 
  // 1-3 attempts: Normal
  // 4-5 attempts: Force 5-minute wait
  // >5 attempts: 24-hour lockout for that number
  if (attempts > 5) {
    return { allowed: false, retryAfter: 86400 };
  } else if (attempts > 3) {
    return { allowed: false, retryAfter: 300 };
  }

  return { allowed: true, retryAfter: 0 };
}

In the frontend, we don't just show a generic "Too many requests" error. We use vernacular-aware messaging: "Network thoda dhima hai" (The network is a bit slow). Please wait 5 minutes before trying again. This reduces the anxiety that leads to repeated tapping.

Handling the "Out-of-Order" OTP Problem

When connectivity is spotty, SMS packets often arrive out of order. If a user requests an OTP at 10:00 AM and another at 10:01 AM, the 10:01 AM message might actually reach the handset first.

If your backend invalidates the previous OTP the moment a new one is requested, you create a race condition that is almost impossible to win on a 2G connection.

The Solution: We maintain a "buffer" of valid OTPs. Instead of a single value in Redis, we store a small array of hashes for that phone number. Any OTP generated in the last 10 minutes is technically valid, but once any of them is used, the entire set is flushed.

// Logic for verifying OTP with a buffer
async function verifyOtp(phoneNumber: string, userSubmittedCode: string) {
  const key = `active_otps:${phoneNumber}`;
  const validCodes = await redis.lrange(key, 0, -1);

  if (validCodes.includes(hash(userSubmittedCode))) {
    await redis.del(key); // Clear all on success
    return { success: true };
  }
  
  return { success: false };
}

The Infrastructure Layer: DLT and SMS Gateways

In India, we have to deal with the Distributed Ledger Technology (DLT) mandate by TRAI. Every SMS template must be pre-registered. For an engineer, this means your "dynamic" messages aren't actually that dynamic.

At KhetiSetu, we found that using a single SMS provider was a single point of failure. During peak harvest seasons, certain gateways crawl to a halt. We implemented a fallback mechanism:

  1. Primary Gateway: High delivery rate, higher cost (e.g., Twilio or local premium providers).
  2. Secondary Gateway: Lower cost, used if the primary returns a non-200 response.
  3. WhatsApp Fallback: If the user has a smartphone (which our Next.js app detects), we offer a "Receive via WhatsApp" button after the first 60 seconds. WhatsApp often delivers over data when cellular SMS protocols are congested.

Designing for "Offline-First" Login

One of the biggest hurdles in agri-tech is that a farmer might lose signal after they've requested the OTP but before they can submit it.

We use a combination of localStorage and a custom React hook to persist the "Verification State." If the farmer's browser refreshes or the phone reboots because of a low battery, the app remembers that an OTP is pending. We don't force them to start the process over; we show them the input field immediately.

Key UX Principles we follow:

  • Auto-focusing the OTP input: Using the autocomplete="one-time-code" attribute so Android devices can pipe the SMS directly into the field.
  • Visual Cues: Using a progress bar instead of a spinning wheel. A spinner looks like a crash; a progress bar looks like work is being done.
  • Zero-Zero-Zero: We ensure our login page is ultra-light. No heavy hero images, no external tracking scripts that block the main thread. When you're on a 20Kbps connection, every kilobyte is a second of waiting.

Conclusion

Building for the next billion users isn't about using the flashiest new framework. It’s about understanding the constraints of the physical world—the distance from the cell tower, the heat of the sun on a screen, and the frustration of a failed login when you're trying to sell your crop.

By implementing adaptive rate-limiting, managing OTP buffers, and respecting the limitations of rural infrastructure, we've reduced our login failure rate by nearly 40%. It’s a reminder that in engineering, empathy for the end-user is just as important as the elegance of the code.

If you're building tools for rural India, stop optimizing for the "happy path" of 5G and start designing for the resilience of the 2G reality.

Direct Kisan Mandi

Sell or Source Direct from Verified Farmers

Connect with verified buyers and sellers across Indian mandis with zero brokerage on KhetiSetu Marketplace.

Explore Marketplace
K

Written by KhetiSetu Agronomy Research Team

Empowering Indian farmers with scientific agronomy, ICAR guidelines, and transparent digital tools.