Package: aiodataloader-ng
DataLoader is a generic utility to be used as part of your application’s
data fetching layer to provide a simplified and consistent API over
various remote data sources such as databases or web services via
batching and caching.A port of the “Loader” API originally developed by [@schrockn][] at
Facebook in 2010 as a simplifying force to coalesce the sundry key-value
store back-end APIs which existed at the time. At Facebook, “Loader”
became one of the implementation details of the “Ent” framework, a
privacy-aware data entity loading and caching layer within web server
product code. This ultimately became the underpinning for Facebook’s
GraphQL server implementation and type definitions.DataLoader is a simplified version of this original idea implemented in
Python for AsyncIO services. DataLoader is often used when implementing
agrapheneservice,
though it is also broadly useful in other situations.DataLoader is provided so that it may be useful not just to build
GraphQL services with AsyncIO but also as a publicly available reference
implementation of this concept in the hopes that it can be ported to
other languages. If you port DataLoader to another language, please open
an issue to include a link from this repository.Getting StartedFirst, install DataLoader using pip.pipinstallaiodataloaderTo get started, create aDataLoader. EachDataLoaderinstance
represents a unique cache. Typically instances are created per request
when used within a web-server likeSanicif different users
can see different things.Note: DataLoader assumes a AsyncIO environment withasync/awaitavailable only in Python 3.5+.BatchingBatching is not an advanced feature, it’s DataLoader’s primary feature.
Create loaders by providing a batch loading function.fromaiodataloaderimportDataLoaderclassUserLoader(DataLoader):asyncdefbatch_load_fn(self,keys):returnawaitmy_batch_get_users(keys)user_loader=UserLoader()A batch loading function accepts a Iterable of keys, and returns a
Promise which resolves to a List of values*.Then load individual values from the loader. DataLoader will coalesce
all individual loads which occur within a single frame of execution (a
single tick of the event loop) and then call your batch function with
all requested keys.user1_future=user_loader.load(1)user2_future=user_loader.load(2)user1=awaituser1_futureuser2=awaituser2_futureuser1_invitedby=user_loader.load(user1.invited_by_id)user2_invitedby=user_loader.load(user2.invited_by_id)print("User 1 was invited by",awaituser1_invitedby)print("User 2 was invited by",awaituser2_invitedby)A naive application may have issued four round-trips to a backend for
the required information, but with DataLoader this application will make
at most two.DataLoader allows you to decouple unrelated parts of your application
without sacrificing the performance of batch data-loading. While the
loader presents an API that loads individual values, all concurrent
requests will be coalesced and presented to your batch loading function.
This allows your application to safely distribute data fetching
requirements throughout your application and maintain minimal outgoing
data requests.Batch FunctionA batch loading function accepts an List of keys, and returns a Future
which resolves to an List of values. There are a few constraints that
must be upheld:The List of values must be the same length as the List of keys.Each index in the List of values must correspond to the same index in
the List of keys.For example, if your batch function was provided the List of keys:[ 2, 9, 6, 1 ], and loading from a back-end service returned the
values:{'id':9,'name':'Chicago'}{'id':1,'name':'New York'}{'id':2,'name':'San Francisco'}Our back-end service returned results in a different order than we
requested, likely because it was more efficient for it to do so. Also,
it omitted a result for key6, which we can interpret as no value
existing for that key.To uphold the constraints of the batch function, it must return an List
of values the same length as the List of keys, and re-order them to
ensure each index aligns with the original keys[ 2, 9, 6, 1 ]:[{'id':2,'name':'San Francisco'},{'id':9,'name':'Chicago'},None,{'id':1,'name':'New York'}]CachingDataLoader provides a memoization cache for all loads which occur in a
single request to your application. After.load()is called once
with a given key, the resulting value is cached to eliminate redundant
loads.In addition to relieving pressure on your data storage, caching results
per-request also creates fewer objects which may relieve memory pressure
on your application:user_future1=user_loader.load(1)user_future2=user_loader.load(1)assertuser_future1==user_future2Caching per-RequestDataLoader cachingdoes notreplace Redis, Memcache, or any other
shared application-level cache. DataLoader is first and foremost a data
loading mechanism, and its cache only serves the purpose of not
repeatedly loading the same data in the context of a single request to
your Application. To do this, it maintains a simple in-memory
memoization cache (more accurately:.load()is a memoized function).Avoid multiple requests from different users using the DataLoader
instance, which could result in cached data incorrectly appearing in
each request. Typically, DataLoader instances are created when a Request
begins, and are not used once the Request ends.For example, when using withSanic:defcreate_loaders(auth_token){return{'users':user_loader,}}app=Sanic(__name__)@app.route("/")asyncdeftest(request):auth_token=authenticate_user(request)loaders=create_loaders(auth_token)returnrender_page(request,loaders)Clearing CacheIn certain uncommon cases, clearing the request cache may be necessary.The most common example when clearing the loader’s cache is necessary is
after a mutation or update within the same request, when a cached value
could be out of date and future loads should not use any possibly cached
value.Here’s a simple example using SQL UPDATE to illustrate.# Request begins...user_loader=...# And a value happens to be loaded (and cached).user4=awaituser_loader.load(4)# A mutation occurs, invalidating what might be in cache.awaitsql_run('UPDATE users WHERE id=4 SET username="zuck"')user_loader.clear(4)# Later the value load is loaded again so the mutated data appears.user4=awaituser_loader.load(4)# Request completes.Caching ExceptionsIf a batch load fails (that is, a batch function throws or returns a
rejected Promise), then the requested values will not be cached. However
if a batch function returns anExceptioninstance for an individual
value, thatExceptionwill be cached to avoid frequently loading the
sameException.In some circumstances you may wish to clear the cache for these
individual Errors:try:user_loader.load(1)exceptExceptionase:user_loader.clear(1)raiseDisabling CacheIn certain uncommon cases, a DataLoader whichdoes notcache may be
desirable. CallingDataLoader(batch_fn, cache=false)will ensure
that every call to.load()will produce anewFuture, and
requested keys will not be saved in memory.However, when the memoization cache is disabled, your batch function
will receive an array of keys which may contain duplicates! Each key
will be associated with each call to.load(). Your batch loader
should provide a value for each instance of the requested key.For example:classMyLoader(DataLoader):cache=Falseasyncdefbatch_load_fn(self,keys):print(keys)returnkeysmy_loader=MyLoader()my_loader.load('A')my_loader.load('B')my_loader.load('A')# > [ 'A', 'B', 'A' ]More complex cache behavior can be achieved by calling.clear()or.clear_all()rather than disabling the cache completely. For
example, this DataLoader will provide unique keys to a batch function
due to the memoization cache being enabled, but will immediately clear
its cache when the batch function is called so later requests will load
new values.classMyLoader(DataLoader):cache=Falseasyncdefbatch_load_fn(self,keys):self.clear_all()returnkeysAPIclass DataLoaderDataLoader creates a public API for loading data from a particular data
back-end with unique keys such as theidcolumn of a SQL table or
document name in a MongoDB database, given a batch loading function.EachDataLoaderinstance contains a unique memoized cache. Use
caution when used in long-lived applications or those which serve many
users with different access permissions and consider creating a new
instance per web request.new DataLoader(batch_load_fn, **options)Create a newDataLoadergiven a batch loading function and options.batch_load_fn: An async function (coroutine) which accepts an
List of keys and returns a Future which resolves to an List of
values.options:batch: DefaultTrue. Set toFalseto disable batching,
instead immediately invokingbatch_load_fnwith a single load
key.max_batch_size: DefaultInfinity. Limits the number of items
that get passed in to thebatch_load_fn.cache: DefaultTrue. Set toFalseto disable memoization
caching, instead creating a new Promise and new key in thebatch_load_fnfor every load of the same key.cache_key_fn: A function to produce a cache key for a given load
key. Defaults tokey => key. Useful to provide when Python
objects are keys and two similarly shaped objects should be
considered equivalent.cache_map: An instance ofdict(or an object with a similar API) to be used as the underlying cache
for this loader. Default{}.load(key)Loads a key, returning aFuturefor the value represented by that
key.key: An key value to load.load_many(keys)Loads multiple keys, promising an array of values:a,b=awaitmy_loader.load_many(['a','b']);This is equivalent to the more verbose:fromasyncioimportgathera,b=awaitgather(my_loader.load('a'),my_loader.load('b'))keys: A list of key values to load.clear(key)Clears the value atkeyfrom the cache, if it exists. Returns itself
for method chaining.key: An key value to clear.clear_all()Clears the entire cache. To be used when some event results in unknown
invalidations across this particularDataLoader. Returns itself for
method chaining.prime(key, value)Primes the cache with the provided key and value. If the key already
exists, no change is made. (To forcefully prime the cache, clear the key
first withloader.clear(key).prime(key,value).) Returns itself for
method chaining.Using with GraphQLDataLoader pairs nicely well withGraphQL. GraphQL fields
are designed to be stand-alone functions. Without a caching or batching
mechanism, it’s easy for a naive GraphQL server to issue new database
requests each time a field is resolved.Consider the following GraphQL request:{
  me {
    name
    bestFriend {
      name
    }
    friends(first: 5) {
      name
      bestFriend {
        name
      }
    }
  }
}Naively, ifme,bestFriendandfriendseach need to request
the backend, there could be at most 13 database requests!When using DataLoader, we could define theUsertype using theSQLiteexample with clearer code and at most 4
database requests, and possibly fewer if there are cache hits.classUser(graphene.ObjectType):name=graphene.String()best_friend=graphene.Field(lambda:User)friends=graphene.List(lambda:User)defresolve_best_friend(self,args,context,info):returnuser_loader.load(self.best_friend_id)defresolve_friends(self,args,context,info):returnuser_loader.load_many(self.friend_ids)Common PatternsCreating a new DataLoader per request.In many applications, a web server using DataLoader serves requests to
many different users with different access permissions. It may be
dangerous to use one cache across many users, and is encouraged to
create a new DataLoader per request:defcreate_loaders(auth_token):return{'users':DataLoader(lambdaids:gen_users(auth_token,ids)),'cdn_urls':DataLoader(lambdaraw_urls:gen_cdn_urls(auth_token,raw_urls)),'stories':DataLoader(lambdakeys:gen_stories(auth_token,keys)),}}# When handling an incoming web request:loaders=create_loaders(request.query.auth_token)# Then, within application logic:user=awaitloaders.users.load(4)pic=awaitloaders.cdn_urls.load(user.raw_pic_url)Creating an object where each key is aDataLoaderis one common
pattern which provides a single value to pass around to code which needs
to perform data loading, such as part of theroot_valuein a
[graphql][] request.Loading by alternative keys.Occasionally, some kind of value can be accessed in multiple ways. For
example, perhaps a “User” type can be loaded not only by an “id” but
also by a “username” value. If the same user is loaded by both keys,
then it may be useful to fill both caches when a user is loaded from
either source:asyncdefuser_by_id_batch_fn(ids):users=awaitgen_users_by_id(ids)foruserinusers:username_loader.prime(user.username,user)returnusersuser_by_id_loader=DataLoader(user_by_id_batch_fn)asyncdefusername_batch_fn(names):users=awaitgen_usernames(names)foruserinusers:user_by_id_loader.prime(user.id,user)returnusersusername_loader=DataLoader(username_batch_fn)Custom CachesDataLoader can optionaly be provided a custom dict instance to use as
its memoization cache. More specifically, any object that implements the
methodsget(),set(),delete()andclear()can be
provided. This allows for custom dicts which implement variouscache
algorithmsto be
provided. By default, DataLoader uses the standarddictwhich simply grows until the DataLoader is released. The default is
appropriate when requests to your application are short-lived.Video Source Code WalkthroughDataLoader Source Code Walkthrough (YouTube):