We wanted to remove embedding and reranking from the application process without replacing a vendor invoice with an unpredictable GPU queue.
Batching requires workload-specific validation
TEI offers token-based batching and admission control, but single-GPU co-serving needs simultaneous-load testing before its latency and capacity trade-offs can be approved.
Those are different workloads. Document ingestion wants sustained throughput. Query embedding wants a short, predictable response. Reranking evaluates a query against every candidate document; a top-50 request creates 50 cross-encoder pairs, not one reusable vector. Mixing all three behind an unrestricted queue is how a cheap retrieval service becomes an expensive latency problem.
Hugging Face Text Embeddings Inference—TEI—addresses the serving layer: tokenization, token-based dynamic batching, admission control, model execution, and HTTP responses. We evaluate it here as infrastructure, not as a recommendation to change embedding models. Our chunking review covers another variable that directly changes its workload: sequence length.
Our assessment is conditional: TEI is a credible dedicated serving engine, but single-GPU embedding-plus-reranking needs workload-specific approval.
An important evidence boundary: our review environment could not launch Docker or fetch model artifacts. We therefore did not complete a TEI execution, GPU latency sweep, OOM reproduction, or cold-start measurement. The commands below are a reproducible deployment and acceptance harness—not a retrospective account of successful runs. We will not turn capacity estimates into measurements.
Two corrections also matter before deployment:
text-embeddings-router``--api-key; authentication is Those distinctions are more useful than a confident but unsupported performance score.
We would start with the official TEI repository and Quick Tour, using separate embedder and reranker containers.
For the CPU smoke test, our deployment recipe uses the CPU image family. For NVIDIA execution, it uses cuda-1.10, NVIDIA Container Toolkit, and drivers compatible with CUDA 12.2 or later. Check the supported hardware matrix before selecting an image for a particular GPU.
set -eu
mkdir -p data
export MODEL_ID=BAAI/bge-base-en-v1.5
export MODEL_REVISION="$(
curl -fsSL "https://huggingface.co/api/models/$MODEL_ID" |
python3 -c 'import json,sys; print(json.load(sys.stdin)["sha"])'
)"
export IMAGE=ghcr.io/huggingface/text-embeddings-inference:cpu-1.10
docker pull "$IMAGE"
docker image inspect "$IMAGE" --format '{{json .RepoDigests}}'
docker run -d --name tei-embed \
-p 127.0.0.1:8080:80 \
-v "$PWD/data:/data" \
"$IMAGE" \
--model-id "$MODEL_ID" \
--revision "$MODEL_REVISION" \
--max-batch-tokens 4096 \
--max-concurrent-requests 32
until curl -fsS http://127.0.0.1:8080/health >/dev/null; do
sleep 1
done
curl -fsS http://127.0.0.1:8080/embed \
-H 'Content-Type: application/json' \
-d '{"inputs":["What is deep learning?","A neural network example."],
"truncate":false,"normalize":true}' |
python3 -c '
import json, sys
vectors = json.load(sys.stdin)
print(json.dumps({
"vectors": len(vectors),
"dimensions": [len(v) for v in vectors]
}))
'
Illustrative output, not captured execution:
{"vectors": 2, "dimensions": [768, 768]}
For a GPU run, replace the image with ghcr.io/huggingface/text-embeddings-inference:cuda-1.10 and add --gpus all. Record the resolved image digest and model commit; a mutable tag alone is not a benchmark identity.
For a native installation, we would follow the repository’s backend-specific local build instructions, then inspect and launch the actual executable:
text-embeddings-router --help
text-embeddings-router \
--model-id BAAI/bge-base-en-v1.5 \
--revision "$MODEL_REVISION" \
--port 8080 \
--max-batch-tokens 4096 \
--max-concurrent-requests 32
We would not substitute an unrelated Python package merely because its name resembles the project.
Our /embed request uses:
{
"inputs": ["first text", "second text"],
"truncate": false,
"normalize": true
}
inputs also accepts a single string. The response is a JSON array of vectors, in input order:
number[][]
Even a single input returns an outer array. There is no OpenAI-style data envelope on this native route.
Pooling is a server/model configuration, not a field in this request. Without an override, TEI reads the model’s pooling configuration. --pooling cls, mean, or last-token changes aggregation; splade requires a compatible masked-language-model architecture and is not interchangeable with ordinary dense pooling.
For reranking, we would start another container on port 8081 with --model-id BAAI/bge-reranker-base, its own pinned revision, and independent limits:
curl -fsS http://127.0.0.1:8081/rerank \
-H 'Content-Type: application/json' \
-d '{
"query":"What is deep learning?",
"texts":["A bread recipe.","A method using layered neural networks."],
"truncate":false,
"raw_scores":true,
"return_text":true
}'
The native response is an array of ranked objects containing index and score; requesting returned text adds text. index refers to the original candidate position. We would preserve that index rather than assuming response order matches request order.
We intentionally specify truncation instead of depending on defaults. We configure truncation explicitly: the current interface defaults to automatic truncation, unlike the behavior used in the 2023 deployment example. We have not verified that default in a local execution. For reranking, the relevant length is the tokenized query-document pair, including special tokens.
Our harness below measures client-visible latency, successful-request throughput, and locally counted input tokens. Save it as bench.py; install httpx and transformers. It performs real requests and does not generate synthetic timing results.
import asyncio
import json
import math
import os
import time
import httpx
from transformers import AutoTokenizer
model = os.environ["MODEL_ID"]
revision = os.environ["MODEL_REVISION"]
url = os.getenv("URL", "http://127.0.0.1:8080/embed")
mode = os.getenv("MODE", "embed")
batch = int(os.getenv("CLIENT_BATCH", "1"))
count = int(os.getenv("REQUESTS", "1000"))
tok = AutoTokenizer.from_pretrained(model, revision=revision)
query = "How does token-based batching affect retrieval latency?"
doc = "Inference servers group independent inputs into batches. " * 20
texts = [doc] * batch
payload = (
{"inputs": texts, "truncate": False, "normalize": True}
if mode == "embed"
else {"query": query, "texts": texts,
"truncate": False, "raw_scores": True}
)
tokens_per_request = sum(
len(tok(t)["input_ids"]) if mode == "embed"
else len(tok(query, t)["input_ids"])
for t in texts
)
def percentile(values, p):
values = sorted(values)
return values[max(0, math.ceil(len(values) * p) - 1)]
async def run(concurrency):
latencies, errors = [], {}
next_request = 0
async with httpx.AsyncClient(timeout=60) as client:
for _ in range(20):
r = await client.post(url, json=payload)
r.raise_for_status()
async def worker():
nonlocal next_request
while next_request < count:
next_request += 1
start = time.perf_counter()
try:
r = await client.post(url, json=payload)
r.raise_for_status()
r.json()
latencies.append((time.perf_counter() - start) * 1000)
except Exception as exc:
key = (
str(exc.response.status_code)
if isinstance(exc, httpx.HTTPStatusError)
else type(exc).__name__
)
errors[key] = errors.get(key, 0) + 1
start = time.perf_counter()
await asyncio.gather(*(worker() for _ in range(concurrency)))
elapsed = time.perf_counter() - start
result = {
"budget": os.getenv("BUDGET"),
"concurrency": concurrency,
"client_batch": batch,
"successes": len(latencies),
"errors": errors,
"requests_s": len(latencies) / elapsed,
"input_tokens_s": len(latencies) * tokens_per_request / elapsed,
"p50_ms": percentile(latencies, 0.50) if latencies else None,
"p95_ms": percentile(latencies, 0.95) if latencies else None,
}
print(json.dumps(result), flush=True)
for concurrency in (1, 4, 16, 32, 64):
asyncio.run(run(concurrency))
We would restart the server at batch-token budgets 4096, 8192, and 16384, repeating each sweep with client batches 1, 8, and 32. BUDGET is a result label; it does not reconfigure a running server. Keep model revision, input corpus, precision, and admission limit fixed.
This is a closed-loop saturation test, not a realistic arrival distribution. Our final gate would add paced traffic, bursts, variable lengths, and repeated runs. We would collect server metrics/traces for queueing and inference time: client p95 includes transport, tokenization, queueing, execution, and serialization, so it is not a per-request GPU inference measurement.
Our immediate roadblock was the unavailable runtime. That prevented us from validating the following failure modes experimentally. We treat them as acceptance tests, not incidents we can claim to have reproduced.
--max-batch-tokens defaults to 16384 in the supplied interface. It limits potential tokens per batch, not total process memory. TEI cannot automatically infer the safe ceiling.
Our mitigation would be to increase the budget only while monitoring device memory, rejection counts, and p95. Concurrency supplies enough queued work to fill larger batches; it does not necessarily create one parallel GPU execution per HTTP request.
On a shared GPU, two individually safe configurations can still exceed the combined memory envelope. We would test long-input mixtures and simultaneous bursts, then retain headroom. We cannot supply a universal OOM threshold.
We would also keep the budget large enough for accepted sequences. Current startup validation with automatic truncation disabled can reject configurations where the model maximum exceeds the budget. We would not present older long-request-stall behavior as a verified current-version bug.
Overriding CLS pooling with mean pooling can still return the expected vector dimensions. A shape-only health check will not catch semantic incompatibility with an existing index.
Our check would compare fixed texts against a trusted model implementation, then run retrieval-quality tests. We would compare cosine similarity, L2 distance, and ranking changes—not invent a divergence percentage. Model revision, pooling, normalization, and prompt policy belong in the index version.
For a single-output reranker, raw_scores:true exposes logits; normalized scores use sigmoid. That monotonic transformation should preserve ordering, but thresholds change.
We would request both modes on identical candidates and verify the relationship. We would not carry a hosted provider’s relevance threshold into TEI merely because both responses contain a field called score. We have no matched hosted-versus-local experiment establishing a particular discrepancy.
We would measure image acquisition, empty-cache startup, cached-weight startup, readiness, and first inference separately. No measured seconds-to-ready figure is available here.
For security, the important distinction is default-open, not “authentication impossible.” We would enable --api-key or API_KEY, keep the service private, and terminate TLS at the ingress. A Hub token downloads models; it does not authenticate inference clients.
Shared-key auth also does not replace tenant quotas or rate limits. Our Docker MCP boundary review applies the same principle: containerization alone is not an access-control boundary.
We would not choose a batch-token budget by maximizing tokens per second alone. Our production objective is maximum successful throughput inside the latency target.
| Option | What we gain | What we must operate or validate |
|---|---|---|
| TEI on CPU | Dedicated serving without a GPU; useful smoke-test path | CPU capacity, backend compatibility, actual online p95 |
| TEI on a dedicated GPU | Token-based batching and independent admission control | GPU cost, safe batch budget, quality parity |
| Two TEI containers sharing one GPU | Potentially better utilization of one device | Memory competition and cross-workload tail latency |
| Application-local encoding | Minimal initial deployment machinery | Batching across processes, model duplication, backpressure |
| Managed embedding/rerank API | Less infrastructure ownership | Current pricing, quotas, data policy, score/model differences |
| Managed TEI endpoint | Managed lifecycle around the serving engine | Instance utilization, cold starts, service configuration |
For scale context, we evaluated a historical managed-endpoint benchmark: 450+ requests/s for BAAI/bge-base-en-v1.5 at 512 tokens and batch size 32 on an NVIDIA A10G Inference Endpoint. We retain its October 2023 conditions; we did not reproduce it locally, and we do not use it as a self-hosted result, a p95 promise, or a 2026 price quote.
In our illustrative batching calculation, we use a fixed cost of 4 ms and a marginal cost of 0.5 ms per sequence, following this batching model. We calculate approximately 222 sequences/s at batch 1 and 1,600 sequences/s at batch 32—about 7.2× throughput. These are assumed-cost calculations, not measured TEI performance.
We would run embedding alone, reranking alone, and both simultaneously at the intended traffic mix. Then we would compare each workload’s p95, errors, throughput, and peak memory.
Two containers provide independent queues, not GPU scheduling isolation. We would cap rerank candidates and pair lengths, protect online embedding capacity, and move bulk ingestion elsewhere before assuming shared-device economics work.
Let hourly all-in infrastructure cost be (H), and sustained successful throughput be (T) input tokens/s:
[
\text{cost per million tokens}
=\frac{H \times 1{,}000{,}000}{3600T}
]
For an illustrative assumption, $0.80/hour at 20,000 tokens/s gives approximately $0.0111 per million tokens. Averaging only 2,000 tokens/s raises it to $0.111. Neither throughput is a TEI measurement.
At $0.80/hour, a 730-hour month costs $584 before engineering and ancillary infrastructure. Against a hypothetical vendor price of $0.10 per million tokens, infrastructure-only break-even is 5.84 billion tokens/month.
We would use current vendor quotes and measured utilization before approving a migration. Reranking needs separate accounting per search or per candidate pair; combining it with embeddings in one tokens-per-dollar headline hides the actual workload.
We would deploy TEI when:
We would hold off on single-GPU co-serving when:
Our conclusion is not “TEI is slow” or “TEI is cheaper.” It is that TEI exposes the right controls for a serious serving evaluation, while leaving capacity planning and workload isolation with us.
We would start from the official deployment path, run the sweep, and approve co-serving only after simultaneous-load results pass. Until then, single-GPU savings remain a hypothesis—not a production commitment.