ipasis
Blog/Engineering Patterns

Architecting Low-Latency IP Intelligence for Real-Time Security

February 23, 20265 min read

In modern distributed systems, the decision to allow, challenge, or block a request often happens within a window of milliseconds. Whether it is Real-Time Bidding (RTB) in ad-tech, high-frequency trading compliance, or adaptive authentication flows, integrating IP intelligence (proxy detection, geo-location, ASN analysis) must incur minimal latency overhead.

This guide explores architectural patterns for integrating IPASIS into real-time decision loops without compromising system throughput.

The Latency Budget

When adding external API calls to the critical path of a request lifecycle, network latency is the primary constraint. If your SLA requires a response time of < 200ms, and your database operations take 50ms, your budget for third-party intelligence is tight.

To maintain performance, engineers must implement:

  1. Asynchronous Lookups: Avoid blocking the main thread.
  2. Aggressive Caching: Store IP metadata locally (Redis/Memcached).
  3. Circuit Breaking: Fail open or closed gracefully if the API times out.

Implementation: Asynchronous Middleware

Directly awaiting an API call on every HTTP ingress is an anti-pattern. Instead, use a tiered approach: check the cache first, then query the provider asynchronously if the cache misses.

Node.js Example: Express Middleware with Redis

The following example demonstrates an Express middleware that checks a local Redis cache before querying IPASIS. It utilizes a short-circuit logic: if the IP is known to be a datacenter proxy, block immediately.

const axios = require('axios');
const redis = require('redis');
const client = redis.createClient();

const CHECK_TIMEOUT = 100; // ms

async function ipRiskMiddleware(req, res, next) {
  const ip = req.ip;
  
  // 1. Check Cache (Fast Path)
  const cachedData = await client.get(`ip:${ip}`);
  if (cachedData) {
    const data = JSON.parse(cachedData);
    if (data.is_proxy || data.is_vpn) {
      return res.status(403).json({ error: 'Anonymizer detected' });
    }
    return next();
  }

  // 2. Query IPASIS API (Slow Path)
  try {
    const response = await axios.get(`https://api.ipasis.com/v1/ip/${ip}`, {
        headers: { 'X-API-KEY': process.env.IPASIS_KEY },
        timeout: CHECK_TIMEOUT // Strict timeout enforcement
    });

    const { is_proxy, is_vpn, country_code } = response.data;

    // 3. Cache Result (TTL: 1 hour)
    client.setEx(`ip:${ip}`, 3600, JSON.stringify(response.data));

    if (is_proxy || is_vpn) {
      return res.status(403).json({ error: 'Anonymizer detected' });
    }
  } catch (error) {
    // Fail Open strategy: Allow traffic if API fails/times out to preserve UX
    console.error('IP Intelligence lookup failed:', error.message);
  }

  next();
}

Handling Concurrency in Go

For high-throughput systems written in Go, utilizing goroutines and context cancellation is standard practice to prevent thread exhaustion during network I/O.

Go Example: Context with Timeout

package main

import (
	"context"
	"encoding/json"
	"net/http"
	"time"
)

type IPResponse struct {
	IsProxy bool   `json:"is_proxy"`
	IsVPN   bool   `json:"is_vpn"`
	Country string `json:"country_code"`
}

func checkIP(ip string) (*IPResponse, error) {
	ctx, cancel := context.WithTimeout(context.Background(), 150*time.Millisecond)
	defer cancel()

	req, _ := http.NewRequestWithContext(ctx, "GET", "https://api.ipasis.com/v1/ip/"+ip, nil)
	req.Header.Set("X-API-KEY", "YOUR_KEY")

	client := &http.Client{}
	res, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer res.Body.Close()

	var data IPResponse
	if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
		return nil, err
	}
	return &data, nil
}

Decision Logic: Beyond Binary Blocking

Simply blocking all VPNs is rarely the optimal business strategy. Use the granular data returned by IPASIS to build a weighted risk score.

| Signal | Action | Use Case | | :--- | :--- | :--- | | Hosting/Datacenter IP | Block | Prevent bot scraping from AWS/GCP instances. | | Residential Proxy | CAPTCHA | Likely a bot, but could be an infected user device. | | Public VPN | 2FA Challenge | User privacy tool; allow login but require step-up auth. | | Mismatched Geo | Flag | User IP country differs from billing address. |

FAQ

How does IP intelligence affect API latency?

With proper implementation, the impact is negligible. By using persistent connections (Keep-Alive) and caching results for common IPs, the P99 latency added to a request flow should remain under 50ms.

Should I cache results indefinitely?

No. IP ownership changes dynamically (DHCP). We recommend a TTL (Time-To-Live) of 1 to 24 hours depending on your strictness requirements. Hosting ranges (Datacenter IPs) are static longer than residential IPs.

What is the Fail-Open vs. Fail-Closed strategy?

  • Fail-Open: If the IP API times out, allow the user. Best for e-commerce (don't lose the sale).
  • Fail-Closed: If the IP API times out, block the user. Best for admin panels or high-security fintech endpoints.

Secure Your Perimeter with IPASIS

Stop relying on outdated GeoIP databases. Integrate real-time proxy, VPN, and tor detection directly into your application logic.

Get your API Key and start filtering traffic in minutes.

Start detecting VPNs and Bots today.

Identify anonymized traffic instantly with IPASIS.

Get API Key