ipasis
Blog/Security Engineering

Architecting an IP Intelligence Layer for Application Security

March 04, 20268 min read

Modern application security relies on context. Evaluating a request solely on payload validity is no longer sufficient; you must evaluate the origin of the request. Building an IP Intelligence Layer into your stack allows you to make real-time decisions based on metadata such as connection type (VPN/Proxy), ISP reputation, and geolocation.

This guide outlines the architecture for integrating IP intelligence as a high-performance middleware layer.

Architectural Placement

To minimize latency and protect core resources, the IP intelligence layer should sit at the Edge or within your API Gateway/Ingress Controller. Placing it deep within business logic consumes unnecessary compute resources for bad traffic.

Recommended Flow:

  1. Ingress: Request hits Load Balancer (Nginx/HAProxy/AWS ALB).
  2. Middleware: Request is intercepted by the IP Intelligence Layer.
  3. Enrichment: Middleware queries IP data (checking Cache first, then Provider).
  4. Decision: Block, Challenge (CAPTCHA), or Pass.
  5. Application: Enriched request reaches core logic.

Implementation Strategy: The Look-Aside Cache Pattern

Querying an external API for every incoming request introduces unacceptable latency. You must implement a Look-Aside Cache strategy using Redis or Memcached.

The Workflow

  1. Extract client IP from X-Forwarded-For or socket connection.
  2. Check Redis for ip_metadata:{ip}.
  3. Hit: Return metadata immediately.
  4. Miss: Async/Sync query to IPASIS API, store in Redis with TTL (e.g., 24 hours), return metadata.

Code Example: Python (FastAPI + Redis)

Below is a production-ready pattern for a FastAPI dependency that enforces a 'No VPN' policy.

import os
import redis
import httpx
from fastapi import Request, HTTPException, status

# Configuration
REDIS_HOST = os.getenv("REDIS_HOST", "localhost")
IPASIS_API_KEY = os.getenv("IPASIS_API_KEY")
CACHE_TTL = 86400  # 24 hours

# Initialize Redis
cache = redis.Redis(host=REDIS_HOST, port=6379, db=0)

async def get_ip_intelligence(ip: str):
    """Retrieve IP data with caching strategy."""
    cache_key = f"ip_intel:{ip}"
    
    # 1. Check Cache
    cached_data = cache.get(cache_key)
    if cached_data:
        return eval(cached_data)  # In production, use json.loads

    # 2. Query IPASIS (Cache Miss)
    async with httpx.AsyncClient() as client:
        resp = await client.get(
            f"https://api.ipasis.com/v2/ip/{ip}",
            headers={"X-Api-Key": IPASIS_API_KEY}
        )
        
    if resp.status_code != 200:
        return None # Fail open or closed depending on security posture
        
    data = resp.json()
    
    # 3. Set Cache
    cache.setex(cache_key, CACHE_TTL, str(data))
    return data

async def enforce_clean_ip(request: Request):
    """Middleware dependency to block VPNs."""
    client_ip = request.client.host 
    # Note: In production, parse X-Forwarded-For based on trusted proxy count
    
    metadata = await get_ip_intelligence(client_ip)
    
    if not metadata:
        return # Allow traffic if API fails (Fail Open)
        
    # Policy Definition
    security = metadata.get('security', {})
    if security.get('is_vpn') or security.get('is_proxy'):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Anonymizers are not permitted."
        )

Handling IPv6 and Rate Limiting

When building this layer, consider:

  1. IPv6 Formatting: Ensure your cache keys normalize IPv6 addresses (e.g., expanding compressed blocks) to prevent cache fragmentation.
  2. Fail-Open vs. Fail-Closed:
    • Fail-Open: If the IP API is down, allow traffic. Preferred for e-commerce to avoid revenue loss.
    • Fail-Closed: If the IP API is down, block traffic. Preferred for high-security admin panels.

Frequently Asked Questions

Q: What is the latency impact of this layer? With a proper Redis implementation, cache hits add <2ms. Cache misses depend on the provider; IPASIS endpoints typically respond in <80ms globally.

Q: How do I handle dynamic IPs? Set your Cache TTL appropriately. A 24-hour TTL is standard for ISP data, but for threat intelligence (like scraping botnets), a shorter TTL (1-6 hours) ensures you catch rotating IPs quickly.

Q: Should I block all Data Center IPs? Generally, yes. Legitimate users connect via ISPs (Residential/Mobile). Traffic originating from AWS, DigitalOcean, or Linode is almost always automated/bot traffic.

Secure Your Stack with IPASIS

Building an intelligence layer is only as effective as the data feeding it. IPASIS provides enterprise-grade accuracy for VPN, Proxy, and Tor node detection with low-latency global endpoints.

Stop fraudsters at the gate. Get your API Key from IPASIS and start filtering traffic today.

Start detecting VPNs and Bots today.

Identify anonymized traffic instantly with IPASIS.

Get API Key