Skip to main content

Okustera Document Intelligence & Vector Lakehouse

An enterprise-grade, zero-license-tax Document Intelligence & Vector Lakehouse deployed on the Okustera Cloud platform.

This reference architecture ingests, validates, extracts, and indexes sensitive business documents (such as invoices, legal contracts, KYC records, and healthcare claims) into searchable relational data in Managed PostgreSQL and semantic vector embeddings in Managed Qdrantβ€”completely isolated within European sovereign cloud infrastructure with zero external cloud leakage.

A live, publicly accessible instance of this workload is published at:

🌐 Live Application Dashboard: https://doclake.okustera.com


1. System Architecture & Component Overview​


2. Interactive Web UI Dashboard​

The reference workload includes an interactive web dashboard served over HTTPS (Port 443) at https://doclake.okustera.com/:

  • Live Telemetry KPI Cards: Real-time counters for landed documents, edge gateway authorization passes vs. unauthorized rejections, sandboxed serverless invocations, and indexed vector embedding points.
  • Document Ingestion Simulator:
    • Presets for Invoices (tax, VAT, Net 30), Legal Contracts (liability caps, NDA, governing law), and Healthcare Claims (HIPAA, ICD-10).
    • Perimeter security toggle: Test with a Valid X-API-Key vs. Missing/Invalid Key to observe immediate HTTP 401 rejection at the network edge.
  • Pipeline Execution Stepper: Visual progression across:
    1. API Gateway Edge Ingress (WAF & API Key Authentication)
    2. S3 Object Landing (s3://raw-document-lake)
    3. Sandboxed Serverless Parsing (with shared Python data-science dependency layer)
    4. Managed PostgreSQL Storage & Qdrant Vector Upsert
  • Qdrant Semantic Vector Search: Query vectorized document embeddings and inspect similarity scores and snippets.
  • Document Lake Explorer: Browse processed documents, S3 object keys, line/word counts, and extracted text snippets.

3. Core Capabilities Demonstrated​

A. Edge Security & API Governance​

  • Perimeter Defense: Okustera API Gateway enforces automated TLS termination, OWASP WAF inspection, API key authentication, CORS policies, and per-consumer rate limiting (50 req/s, 10 burst).
  • Zero-Trust Micro-Segmentation: Kubernetes NetworkPolicy restricts ingestion workloads so they can communicate only with the API Gateway, S3 Object Storage, and private DNSβ€”blocking access to cloud metadata (169.254.169.254/32).

B. Sovereign Storage & Managed Databases​

  • S3-Compatible Object Storage: Private buckets (raw-document-lake and processed-document-lake) with encryption at rest and predictable transparent pricing.
  • High-Availability Relational & Vector Persistence: Managed PostgreSQL stores structured document metadata while Managed Qdrant indexes dense vector embeddings strictly over private VPC networking.

C. Serverless Extraction with Shared Dependency Layers​

  • Shared Dependency Layers: Rather than bundling heavy libraries (pandas, numpy, boto3, pydantic) into every function package, the doc-extract-worker function attaches a reusable shared dependency layer managed via Terraform or the Cloud Portal.
  • Isolated User-Space Kernel Sandboxing: Untrusted documents are parsed inside hardware-grade user-space kernel sandboxes with automatic scale-to-zero elasticity when idle.

D. Workflow Orchestration (Managed Apache Airflow)​

  • Elastic Task Execution: Runs on-demand task containers for each pipeline step without paying for idle static workers.
  • Integrated Portal & API Management: Upload DAGs via Terraform (okustera_workflow_dag), REST API (POST /api/v1/workflows/dags/upload), or the Cloud Portal UI, and stream task logs directly in the console.

E. Zero-Trust Workload Identity (Pod IAM & STS)​

  • No Static Credentials in Pods: Eliminates hardcoded S3 access keys and long-lived secrets.
  • Short-Lived STS Sessions: Workloads present a short-lived projected OIDC JWT to /api/v1/iam/sts/assume-role and receive 1-hour scoped S3 credentials bound to a least-privilege IAM role.
  • KMS Secret Escrow: Database credentials and API keys are stored securely in the Okustera KMS Secrets Vault.

4. Project Structure​

document-processing-lakehouse/
β”œβ”€β”€ README.md # Architectural and operational guide
β”œβ”€β”€ terraform/
β”‚ β”œβ”€β”€ main.tf # Okustera Terraform Provider setup
β”‚ β”œβ”€β”€ gateway_and_storage.tf # API Gateway route, S3 buckets, IAM role & policies
β”‚ β”œβ”€β”€ serverless_and_workflows.tf # Shared dependency layer, serverless function & Airflow DAG
β”‚ └── databases.tf # Managed PostgreSQL & Qdrant Vector DB resources
β”œβ”€β”€ k8s/
β”‚ β”œβ”€β”€ network-policy.yaml # Zero-trust inter-namespace egress/ingress rules
β”‚ └── intake-deployment.yaml # Document intake service with OIDC token projection
β”œβ”€β”€ app/
β”‚ β”œβ”€β”€ Dockerfile # Multi-stage container build for Python intake service
β”‚ β”œβ”€β”€ requirements.txt # FastAPI, Boto3, Jinja2, Uvicorn dependencies
β”‚ β”œβ”€β”€ main.py # FastAPI intake server & semantic query engine
β”‚ └── templates/
β”‚ └── index.html # Interactive dashboard with live telemetry
β”œβ”€β”€ functions/
β”‚ └── doc-extract-worker/
β”‚ └── handler.py # Python parsing handler running in isolated serverless sandbox
β”œβ”€β”€ dags/
β”‚ └── document_intelligence_pipeline.py # Managed Airflow TaskFlow DAG executing end-to-end pipeline
└── scripts/
└── sts_client.py # Reusable Python STS Token Exchange helper

5. Declarative Configuration & Code Implementation​

A. API Gateway Route & S3 Storage (terraform/gateway_and_storage.tf)​

resource "okustera_s3_bucket" "raw_document_lake" {
name = "raw-document-lake"
acl = "private"
versioning = true
}

resource "okustera_apisix_route" "doclake_api" {
name = "doclake-intake-route"
domain = "doclake.okustera.com"
path = "/api/*"

upstream = {
service_name = "document-intake-service"
port = 8080
timeout = 60
}

tls_enabled = true
cluster_issuer = "letsencrypt-prod"
waf_enabled = true
waf_mode = "Blocking"
cors_enabled = true

rate_limit = {
requests_per_minute = 3000
burst = 10
}
}

B. Serverless Function with Shared Dependency Layer (terraform/serverless_and_workflows.tf)​

resource "okustera_layer" "python_datascience" {
name = "python-datascience"
description = "Shared document analytics layer (numpy, pandas, boto3)"
compatible_runtimes = ["python3-http", "python313"]
}

resource "okustera_layer_version" "python_datascience_v1" {
layer_id = okustera_layer.python_datascience.id
packages = ["boto3==1.35.0", "numpy==2.1.0", "pandas==2.2.2"]
}

resource "okustera_function" "doc_extract_worker" {
name = "doc-extract-worker"
runtime = "python3-http"
handler = "handler.handle"
min_replicas = 0
max_replicas = 10
memory_limit = "1024Mi"
cpu_limit = "1000m"
layer_version_ids = [okustera_layer_version.python_datascience_v1.version]

environment_variables = {
"S3_ENDPOINT_URL" = "https://s3.okustera.com"
}

source_code = file("${path.module}/../functions/doc-extract-worker/handler.py")
}

resource "okustera_workflow_dag" "document_intelligence" {
dag_id = "document_intelligence_pipeline"
filename = "document_intelligence_pipeline.py"
is_paused = false
content = file("${path.module}/../dags/document_intelligence_pipeline.py")
}

C. Serverless Python Handler (functions/doc-extract-worker/handler.py)​

import json
import os
import boto3
import numpy as np

def handle(req: str) -> str:
payload = json.loads(req) if req else {}
bucket_name = payload.get("bucket", "raw-document-lake")
object_key = payload.get("key")

if not object_key:
return json.dumps({"error": "Missing 'key' in request payload"})

s3 = boto3.client(
"s3",
endpoint_url=os.environ.get("S3_ENDPOINT_URL", "https://s3.okustera.com"),
aws_access_key_id=os.environ.get("AWS_ACCESS_KEY_ID"),
aws_secret_access_key=os.environ.get("AWS_SECRET_ACCESS_KEY"),
aws_session_token=os.environ.get("AWS_SESSION_TOKEN"),
)

obj = s3.get_object(Bucket=bucket_name, Key=object_key)
raw_text = obj["Body"].read().decode("utf-8", errors="ignore")

lines = [line.strip() for line in raw_text.splitlines() if line.strip()]
word_counts = [len(line.split()) for line in lines]

analysis = {
"key": object_key,
"line_count": len(lines),
"total_words": int(np.sum(word_counts)) if word_counts else 0,
"mean_words_per_line": float(np.mean(word_counts)) if word_counts else 0.0,
"snippet": lines[:3],
"parsed_by": "Okustera Serverless Functions (Shared Dependency Layer)",
}
return json.dumps(analysis)

D. Managed Airflow Pipeline (dags/document_intelligence_pipeline.py)​

from datetime import datetime, timedelta
import json
import os
import urllib.request
from airflow.decorators import dag, task
from scripts.sts_client import OkusteraSTSClient

default_args = {
"owner": "okustera-data-team",
"depends_on_past": False,
"retries": 2,
"retry_delay": timedelta(minutes=1),
}

@dag(
dag_id="document_intelligence_pipeline",
default_args=default_args,
description="Document Intelligence: S3 -> Serverless FaaS -> PostgreSQL & Qdrant",
schedule="*/15 * * * *",
start_date=datetime(2026, 1, 1),
catchup=False,
max_active_runs=1,
tags=["okustera", "document-lake", "s3", "serverless", "qdrant", "postgres"],
)
def document_intelligence_pipeline():

@task
def scan_s3_intake_bucket() -> list[str]:
sts_helper = OkusteraSTSClient()
s3 = sts_helper.get_scoped_s3_client()
bucket = "raw-document-lake"
response = s3.list_objects_v2(Bucket=bucket, Prefix="incoming/")
keys = [item["Key"] for item in response.get("Contents", []) if not item["Key"].endswith("/")]
print(f"Discovered {len(keys)} documents pending processing via STS session.")
return keys

@task
def invoke_serverless_parser(keys: list[str]) -> list[dict]:
if not keys:
return []

function_url = os.environ["DOC_EXTRACT_FUNCTION_URL"]
api_token = os.environ["OKUSTERA_API_TOKEN"]
results = []
for key in keys:
req_data = json.dumps({"bucket": "raw-document-lake", "key": key}).encode("utf-8")
req = urllib.request.Request(
function_url,
data=req_data,
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {api_token}",
},
method="POST",
)
with urllib.request.urlopen(req, timeout=30) as resp:
output = json.loads(resp.read().decode("utf-8"))
results.append(output)
return results

@task
def store_relational_metadata(records: list[dict]) -> int:
if not records:
return 0
from airflow.providers.postgres.hooks.postgres import PostgresHook
pg_hook = PostgresHook(postgres_conn_id="doclake_postgres_conn")
conn = pg_hook.get_conn()
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS processed_documents (
id SERIAL PRIMARY KEY,
object_key VARCHAR(255) UNIQUE NOT NULL,
line_count INT,
total_words INT,
mean_words_per_line FLOAT,
processed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
""")
for r in records:
cursor.execute("""
INSERT INTO processed_documents (object_key, line_count, total_words, mean_words_per_line)
VALUES (%s, %s, %s, %s)
ON CONFLICT (object_key) DO UPDATE
SET line_count = EXCLUDED.line_count,
total_words = EXCLUDED.total_words,
mean_words_per_line = EXCLUDED.mean_words_per_line,
processed_at = CURRENT_TIMESTAMP;
""", (r["key"], r["line_count"], r["total_words"], r["mean_words_per_line"]))
conn.commit()
cursor.close()
return len(records)

@task
def index_vector_embeddings(records: list[dict]) -> str:
if not records:
return "No records."
qdrant_url = f"{os.environ['QDRANT_ENDPOINT_URL']}/collections/documents/points"
qdrant_api_key = os.environ["QDRANT_API_KEY"]
points = []
for idx, r in enumerate(records):
vec = [float(r["line_count"]), float(r["total_words"]), float(r["mean_words_per_line"]), 1.0]
points.append({
"id": idx + 1,
"vector": vec,
"payload": {"key": r["key"], "summary": r["snippet"]},
})
req = urllib.request.Request(
qdrant_url,
data=json.dumps({"points": points}).encode("utf-8"),
headers={
"Content-Type": "application/json",
"api-key": qdrant_api_key,
},
method="PUT",
)
with urllib.request.urlopen(req, timeout=10) as resp:
print(f"Qdrant response: {resp.status}")
return f"Indexed {len(records)} points."

keys = scan_s3_intake_bucket()
records = invoke_serverless_parser(keys)
saved = store_relational_metadata(records)
indexed = index_vector_embeddings(records)

keys >> records >> saved >> indexed

pipeline = document_intelligence_pipeline()

6. Deployment & Verification Runbook​

Step 1: Provision Infrastructure, Serverless Function & Airflow DAG via Terraform​

cd terraform
terraform init
terraform apply

Step 2: Deploy the Document Intake Service to Kubernetes​

# Create API key secret out-of-band in your application namespace
kubectl create secret generic doclake-api-key \
--from-literal=key="<YOUR_API_KEY>" -n tenant-app

# Apply NetworkPolicy and Intake Deployment manifests
kubectl apply -f k8s/network-policy.yaml
kubectl apply -f k8s/intake-deployment.yaml
kubectl rollout status deployment/document-intake-service -n tenant-app

Step 3: Test Authenticated Ingestion & Trigger the Airflow Pipeline​

# 1. Submit an incoming document via the API Gateway with an API Key
curl -X POST https://doclake.okustera.com/api/v1/documents/upload \
-H "X-API-Key: <YOUR_API_KEY>" \
-F "file=@sample_invoice.txt"

# 2. Trigger the Managed Airflow DAG run via the Okustera REST API
curl -X POST https://portal.okustera.com/api/v1/workflows/dags/document_intelligence_pipeline/trigger \
-H "Authorization: Bearer <YOUR_OKUSTERA_API_TOKEN>" \
-H "Content-Type: application/json" \
-d '{"conf": {}}'

# 3. Inspect DAG run history and task logs via API (or in the Cloud Portal)
curl -H "Authorization: Bearer <YOUR_OKUSTERA_API_TOKEN>" \
https://portal.okustera.com/api/v1/workflows/dags/document_intelligence_pipeline/runs

7. Business Value & Financial ROI​

  • Zero Cloud License & Egress Penalties: Eliminates proprietary hyperscaler document pipeline and egress markups, lowering data pipeline TCO by 40% to 65%.
  • Zero Credential Sprawl: Replaces static access keys with Workload Identity OIDC token projection and temporary 1-hour STS credentials.
  • Rapid Iteration Velocity: Reusable shared dependency layers let data scientists deploy parsing updates in seconds without rebuilding container images.
  • European Regulatory & Privacy Compliance: Aligned with EU GDPR Chapter V, NIS2, and ISO/IEC 27001/27017, keeping sensitive documents strictly within European sovereign infrastructure.