API keys are the authentication mechanism, and the scoping is coarser than IAM-style systems. A key belongs to a project and grants access to that project's indexes; keys can be created and revoked, and recent versions support scoping a key's permissions. The practical consequences: a leaked key exposes every index in the project, so project boundaries are a security boundary and worth using; keys should be per-service rather than shared; and rotation needs a procedure, because an application with a hardcoded key has no rotation story.
Tenant isolation has two options and the choice is a real one.
Namespaces partition one index. A query targets exactly one namespace and cannot see others, they are free, they are created implicitly on first write, and - as Module 4 established - they avoid the filter selectivity penalty entirely. The limitation: isolation is enforced by your application passing the right namespace. There is no key that can only read one namespace, so a bug in your namespace selection is a cross-tenant data leak, and that is the risk to design against with a single code path that derives the namespace from the authenticated identity and never from a request parameter.
Separate indexes per tenant give you key-level isolation and separate scaling, at the cost of per-index overhead, a limit on index count, and much more to operate. The usual guidance: namespaces for many tenants with a shared application, separate indexes for a small number of tenants with genuinely different requirements or a regulatory need for hard separation. State which you chose and why.
Data privacy deserves explicit treatment, because a vector pipeline sends your data to places you should know about. If you use an embedding API, the text of every chunk you index and every query your users type is sent to that provider. For public documentation that may be fine; for customer records, medical notes or anything under a data processing agreement, it is a decision with legal weight. The alternative is a local embedding model, which removes that transfer entirely and is one of the stronger arguments for self-hosted embeddings.
Two more privacy points specific to vectors. First, an embedding is not anonymisation: research has repeatedly shown that text can be partially reconstructed from its embedding, so a vector of sensitive text is sensitive data and should be treated as such. Second, metadata is stored in plain text and is the most likely place for personal data to end up by accident - so the excerpt field deserves the same review as the document itself.
Quotas and monitoring. Serverless indexes have limits on namespaces, metadata size, vector count per index and request rates, and the Pinecone console reports read units, write units and storage. The metrics to watch: read units by index and namespace (your query cost), write units (your ingestion cost), storage growth, request rate against the quota, and error rates by type - with rate limits distinguished from genuine errors.
The cost model is unusual and worth modelling carefully. Serverless bills storage per GB-month, write units for upserts and deletes, and read units for queries - where a read unit scales with the amount of data the query scans, which means top_k, the namespace size and whether you filter all affect the cost of a single query. So a larger top_k costs more, which interacts directly with the Module 4 mitigation of raising top_k to recover recall under a tight filter. That interaction is the thing to model: the fix for a recall problem is a cost increase, and knowing the size of it is the point.
Laboratory exercise 6 - make it defensible.
Create a separate project for the capstone and per-service API keys. Then demonstrate the exposure: show that one key grants access to every index in its project, and document what that means for your project boundaries.
Implement namespace-based tenant isolation with a single code path that derives the namespace from the authenticated identity. Then demonstrate the risk: write a deliberate bug that takes the namespace from a request parameter, show the cross-tenant read, and then show your correct implementation refusing it. This is the laboratory's most important artefact.
Implement the separate-index alternative for one tenant and compare the two on isolation strength, cost and operational overhead.
Document the data flow for privacy: trace exactly what text leaves your boundary, to which provider, for indexing and for querying. Then implement the local-model alternative and show the transfer eliminated.
Configure monitoring with every metric above and a threshold for each.
Then build the cost model: measure read units for queries at top_k of 5, 10, 50 and 100, measure write units for your full ingestion, and project the monthly cost at three traffic levels. Include the cost of the Module 4 filter mitigation - the read-unit increase from raising top_k - and state it as the price of that recall.
Deliverable: the project and key configuration, the key exposure demonstration, the namespace isolation with the deliberate bug and its refusal, the two-isolation comparison, the documented data flow with the local-model alternative, the alert definitions, and the cost model with the filter mitigation priced.
# ==================================================================
# API KEYS: coarser than IAM. A leaked key exposes the PROJECT.
# ==================================================================
# A key belongs to a PROJECT and grants access to THAT PROJECT'S
# INDEXES. So:
# * *** PROJECT BOUNDARIES ARE A SECURITY BOUNDARY *** - use them.
# A separate project for production, for staging, and for
# anything with a different data sensitivity.
# * keys PER SERVICE, not shared across services
# * ROTATION NEEDS A PROCEDURE, because an application with a
# HARDCODED KEY HAS NO ROTATION STORY
#
# Demonstrate the exposure: with one key, list and read EVERY index
# in the project:
pc = Pinecone(api_key=os.environ["PINECONE_API_KEY"])
for ix in pc.list_indexes():
print(ix["name"], pc.Index(ix["name"]).describe_index_stats())
# -> every index, every namespace, every vector count. One key.
# Document what that means for how you partition projects.
# Rotation, as a procedure rather than an aspiration:
# 1. create a second key
# 2. deploy it alongside (read from a secret store, not a constant)
# 3. verify traffic on the new key
# 4. revoke the old key
# 5. verify nothing broke
# An application that reads its key from an environment variable set
# at deploy time can do this. One with a literal cannot.
# ==================================================================
# *** TENANT ISOLATION: TWO OPTIONS, AND THE CHOICE IS REAL. ***
# ==================================================================
# OPTION A - NAMESPACES. Free, implicit, no filter penalty.
#
# *** AND THE ISOLATION IS ENFORCED BY YOUR APPLICATION PASSING THE
# *** RIGHT NAMESPACE. There is NO KEY THAT CAN ONLY READ ONE
# *** NAMESPACE. SO A BUG IN YOUR NAMESPACE SELECTION IS A
# *** CROSS-TENANT DATA LEAK. ***
#
# Design against it with a SINGLE CODE PATH that derives the
# namespace from the AUTHENTICATED IDENTITY and NEVER from a request
# parameter:
def namespace_for(principal) -> str:
# The ONLY place a namespace is computed. Called by the ONLY
# function that queries. Nothing else may pass a namespace.
if not principal or not principal.tenant_id:
raise PermissionError("no tenant on the authenticated principal")
return f"tenant-{principal.tenant_id}"
def search(principal, query: str, top_k: int = 10, flt: dict | None = None):
ns = namespace_for(principal) # <- derived, not passed
qv = model.encode(query, normalize_embeddings=True).tolist()
return index.query(vector=qv, top_k=top_k, namespace=ns,
filter=flt, include_metadata=True)
# *** THE DEMONSTRATION THAT MATTERS MOST IN THIS LABORATORY: ***
#
# the deliberate bug - namespace from the REQUEST:
def search_broken(principal, query, namespace, top_k=10):
qv = model.encode(query, normalize_embeddings=True).tolist()
return index.query(vector=qv, top_k=top_k, namespace=namespace)
#
# search_broken(acme_user, "pricing", namespace="tenant-globex")
# -> *** GLOBEX'S DOCUMENTS, RETURNED TO AN ACME USER, WITH NO
# ERROR ANYWHERE. ***
#
# Then show search() refusing the same thing, because there is
# nowhere to pass it. Grep your codebase for `namespace=` and
# confirm exactly one call site computes it.
# OPTION B - SEPARATE INDEXES per tenant.
# + KEY-LEVEL isolation (a key per project per tenant), separate
# scaling, hard separation for a regulatory requirement
# - per-index overhead, A LIMIT ON INDEX COUNT, and much more to
# operate
pc.create_index(name="docs-tenant-acme", dimension=DIM, metric=METRIC,
spec=ServerlessSpec(cloud="aws", region="us-east-1"))
# *** THE GUIDANCE: NAMESPACES for MANY tenants with a SHARED
# *** application; SEPARATE INDEXES for a SMALL NUMBER of tenants
# *** with genuinely different requirements or a REGULATORY NEED for
# *** hard separation. *** State which you chose and why - this is a
# security review question, not an implementation detail.
# ==================================================================
# *** DATA PRIVACY: TRACE WHAT LEAVES YOUR BOUNDARY. ***
# ==================================================================
# *** IF YOU USE AN EMBEDDING API, THE TEXT OF EVERY CHUNK YOU INDEX
# *** AND EVERY QUERY YOUR USERS TYPE IS SENT TO THAT PROVIDER. ***
#
# INDEX TIME: your documents -> the embedding provider
# QUERY TIME: your users' queries -> the embedding provider
# ALWAYS: vectors + metadata -> Pinecone
#
# For public documentation that may be fine. For customer records,
# medical notes, or anything under a data processing agreement, it
# is a DECISION WITH LEGAL WEIGHT, and it belongs in the security
# review in those words.
#
# THE ALTERNATIVE - a LOCAL model - removes that transfer entirely,
# and is one of the stronger arguments for self-hosted embeddings:
model = SentenceTransformer("sentence-transformers/all-mpnet-base-v2")
# runs on your hardware; nothing leaves for embedding. Only the
# vectors and metadata go to Pinecone.
# TWO MORE PRIVACY POINTS SPECIFIC TO VECTORS:
#
# 1. *** AN EMBEDDING IS NOT ANONYMISATION. *** Research has
# repeatedly shown text can be PARTIALLY RECONSTRUCTED from its
# embedding. So a vector of sensitive text IS SENSITIVE DATA and
# must be treated as such - in your data classification, your
# retention policy and your incident response.
#
# 2. *** METADATA IS STORED IN PLAIN TEXT *** and is the most likely
# place for personal data to END UP BY ACCIDENT. The `excerpt`
# field deserves THE SAME REVIEW AS THE DOCUMENT ITSELF:
def safe_metadata(chunk, doc):
md = {"doc_id": doc["id"], "title": doc["title"],
"section": doc["section"], "published": doc["published_epoch"],
"model": MODEL_NAME, "chunking": CHUNKING_VERSION}
if doc["contains_pii"]:
md["excerpt"] = "" # the id only; fetch the text
md["redacted"] = True # from the document store, under
else: # its own access control
md["excerpt"] = chunk[:400]
return md
# ==================================================================
# QUOTAS AND MONITORING
# ==================================================================
print(index.describe_index_stats())
# namespaces, vector counts, dimension, index fullness
#
# Quotas to know and check against your plan:
# namespaces per index
# metadata size per vector
# vector count per index
# request rate (queries and upserts per second)
# indexes per project
#
# WHAT TO ALERT ON:
# READ UNITS by index and namespace -> your QUERY cost, and a
# spike is usually a top_k
# change or a loop
# WRITE UNITS -> your INGESTION cost
# storage GB -> growth, and the cost
# request rate vs quota -> throttling ahead
# 429 / rate-limit errors -> SEPARATELY from real
# errors, because they mean
# different things
# p99 query latency -> from the client
# *** RECALL, ON A SCHEDULE *** -> run the Module 4 harness against
# production periodically. It is the only metric that detects a
# degradation the service will never report, and it is the one
# monitoring nobody sets up.
# ==================================================================
# *** THE COST MODEL - and the interaction that matters. ***
# ==================================================================
# Serverless bills:
# STORAGE per GB-month
# WRITE UNITS upserts and deletes
# READ UNITS queries - *** AND A READ UNIT SCALES WITH HOW MUCH
# DATA THE QUERY SCANS. ***
#
# Which means top_k, the NAMESPACE SIZE and WHETHER YOU FILTER all
# affect the cost of a SINGLE QUERY. Measure it:
#
# top_k read units/query p95 latency
# 5 ___ ___ ms
# 10 ___ ___ ms
# 50 ___ ___ ms
# 100 ___ ___ ms
#
# *** AND HERE IS THE INTERACTION TO MODEL: *** Module 4's fix for
# the filter selectivity problem was TO RAISE top_k. That fix is a
# COST INCREASE. So:
#
# "under a 1% filter, recall@5 recovers from 0.71 to 0.87 by
# raising top_k from 10 to 100, at N times the read units per
# query - which at our query volume is $X per month. The
# namespace alternative achieves 0.91 at the top_k=10 cost."
#
# *** THAT SENTENCE IS THE POINT OF THE WHOLE COURSE: a relevance
# *** decision, a cost consequence, and a measured alternative. ***
#
# monthly projection, three levels:
# 1k q/day 50k q/day 1M q/day
# read units _____ _____ _____
# write units _____ _____ _____
# storage GB _____ _____ _____
# embedding (API) _____ _____ _____ <- if not local
# reranker compute _____ _____ _____
# est. monthly $_____ $_____ $_____
#
# Note the last two lines: the EMBEDDING and the RERANKER are
# frequently LARGER than the Pinecone bill, and a cost model that
# omits them is modelling the wrong system.
Open this example in the editor and change it. Nothing you type is saved.
Discussion
No questions on this topic yet. Sign in to ask the first one.