GCP Engineer: Designing Dynamic Multi-Tenant Schemas & Async Tasklets with Google Cloud NDB
B2B SaaS platforms running on Google Cloud Datastore (Firestore in Datastore Mode) often need to support tenant-defined custom fields alongside strongly typed core attributes, while batching high-concurrency entity reads and writes without N+1 RPC bottlenecks. As a Google Cloud Platform (GCP) Engineer and Backend Engineer, I architect hybrid Google Cloud NDB (`google.cloud.ndb`) models using `Expando` dynamic properties, automatic two-tier in-context + Redis/Memcache caching, and concurrent `@ndb.tasklet` coroutines.
1. Controlled Dynamic Attributes with `ndb.Expando` & Selective Indexing
Subclasses of `ndb.Expando` allow tenants to attach custom attributes dynamically at runtime, but by default `Expando` indexes every dynamic property—which quickly triggers Cloud Datastore's composite index limits and inflates write costs. Setting `_default_indexed = False` on the `Expando` class ensures custom tenant metadata is stored safely while only explicitly declared search keys consume index writes:
from google.cloud import ndb
class TenantCatalogItem(ndb.Expando):
_default_indexed = False # Prevent dynamic Expando attributes from bloating indexes
tenant_id = ndb.StringProperty(required=True, indexed=True)
sku = ndb.StringProperty(required=True, indexed=True)
price_cents = ndb.IntegerProperty(required=True, indexed=True)
updated_at = ndb.DateTimeProperty(auto_now=True, indexed=True)
@ndb.tasklet
def fetch_items_with_Inventory_async(item_keys: list[ndb.Key]):
# NDB automatically coalesces concurrent get_async calls into a single batch RPC
items = yield [key.get_async() for key in item_keys]
raise ndb.Return([item for item in items if item is not None])
2. Automatic Batching & Two-Tier Context Caching
When multiple `@ndb.tasklet` coroutines call `key.get_async()` within the same event-loop tick, NDB's auto-batcher coalesces those individual reads into a single `LookupRequest` gRPC batch call and caches results in both the request-local context cache and shared Cloud Memorystore—complementing our automated NDB schema diagram generator and Datastore Mode vs. Native Firestore concurrency guide.
Need a GCP Engineer to optimize your Google Cloud NDB and Datastore architecture? Book a 1-Day Engineering Sprint.