dimamik
Vault is a lightweight Elixir library for immutable data storage within a process subtree.
Due to Elixir’s actor model nature, it’s common for a process to have global context that is valid for every function call inside the process and its children.
For example, this context can include:
- A user when processing a request
- A tenant in a multi-tenant application
- Rate limiting buckets/quotas
- Cache namespaces
- API or client versions
- And many more, depending on your application domain
Vault.init/1 provides you a guarantee that the context can only be defined once per existing process subtree, so you won’t override it by accident. This makes it easy to reason about your context origination.
# Initialize vault in parent process
Vault.init(current_user: %{id: 1, first_name: "Alice", role: "admin"})
# Access data from any descendant process, even these not linked!
spawn(fn ->
Vault.get(:current_user) # => %{id: 1, first_name: "Alice", role: "admin"}
Vault.init(current_user: :user) # => raises, because the ancestor already has vault initialized
end)
# Access data from the parent process itself
Vault.get(:current_user) # => %{id: 1, first_name: "Alice", role: "admin"}
In my case, repeatedly passing the user from the connection and GraphQL context into lower-level functions became hard to maintain.
A typical flow involved extracting the user from the Absinthe resolution context, performing substantial business logic, and only at the end persisting data or writing to the audit log - both of which also required the user. Maintaining this plumbing was cumbersome.
Because the user is immutable for the lifetime of the request and retrieved only once, storing it in the process dictionary is an elegant way to eliminate redundant parameters and simplify the overall flow.
This approach does introduce an implicit dependency - the need to understand where the value originates - but since it’s initialized exactly once, the trade-off is acceptable. In most cases, callers can simply read the value without needing to think about its source.
Properties
- Immutability guarantees. Initializes only once per process tree - will raise if one of ancestors already has vault initialized.
- Familiar API - API is the same as for Elixir’s
Mapmodule, except forVault.initpart. - Any child process will have access to the parent’s
Vault. We’re usingProcessTreelibrary by JB Steadman, which does all the heavy lifting of traversing process trees and propagating data back. You can read more about how ancestors are fetched in this amazing blog post by the library’s author. - Once the vault is found on one of the parents, it’s cached (set in the child’s process dict), so next fetches are faster.
- We have a set of
unsafe_*functions to perform updates on already initialized vault. These updates won’t propagate to the children that already initialized the vault.
https://github.com/dimamik/vault
I’m really curious what you guys think!
Trending in Announcing
Other Trending Topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #library
- #deployment
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #podcasts
- #javascript
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixirconf-us
- #ai
- #blog-post
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #hex
- #security
- #metaprogramming










Showing Posts 1 to 10- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
LostKobrakai
I’m not sure using links is a great idea here. Links connect processes in all manner of configurations. There’s no clear parent/child hierarchy there. For that you’d rather want
$ancestorsor$callers(Task — Elixir v1.20.2). Then you’re also no longer traversing a graph, but just a list of parents.dimamik
This is a really great point! I was going back and forth on this initially, and wanted the vault to be as resilient as possible and not be tightened to OTP primitives (for example, I wanted to support
VaultinsideKernel.spawn_link/1,3), so this is why I’ve chosen links.But thinking of this more, and considering your feedback, I’ll release a
0.2.1version which will default to usingancestorsand add an option to use links globally (if needed). What do you think?LostKobrakai
I’d consider
$callersas well. It will open the door for a lot of tooling, which makes use of it.olivermt
A proper Context for liveview!
tfwright
Looks useful. I assume the controversy is that this kind of thing could be seen as counter to FP patterns? I have always followed Plugs model and just passed stuff like this around, but as @olivermt says, LV is another place where it can be quite painful.
garrison
Contexts have a very particular use-case in a React-style engine, namely they allow components to re-render based on dependencies through a memoization barrier, effectively turning the dependency tree into a DAG. You can get pretty far with a tree but the DAG models certain types of dependencies better (theme styling is a common example).
LiveView doesn’t have memoization (though maybe you can do something similar with LiveComponents?), but even if it did the engine has to actually understand the dependency DAG for things to update. If you just write your
assignsinto the process dictionary you can access them in distant children, but they won’t be able to re-render when things change which breaks the entire declarative model.Surface actually tried to hack Contexts onto LV and eventually gave up for this reason.
christhekeele
Looks great! I definitely have a few projects where I’d use a
$callersversion of this!jswanner
I’m pretty sure ProcessTree already does that
olivermt
I want to use it for static data that only loads at mount time. I hacked a bit on the original surface contexts and discussed a lot with marlus.
For certain use cases you dont care about orphaning the tracking like you do if you just pull the context on render in a functional component.
It makes for a lot cleaner design on certain use cases
Asd
Hi, good idea. I have these questions
Process.info(pid, :dictionary)can be a very expensive operation, since it copies the whole dictionary (which can be quite big) into the current process and if thepidprocess is running, VM will block current process until thepidis interrupted, just in order to copy the dictionary.allow(parent_pid, other_pid)which would allowother_pidprocess to access the state of theparent_pidprocess.ais linked with processesbandc. Processbhas keyb_keyset in it’s vault and processchas keyc_keyset in it’s vault. I won’t be able to access both keys in the first call. So, some unexpected link will produce a bug which would be very hard to catchOverall, I wouldn’t use the library in it’s current state, but idea to have some storage which is accessible by direct children of the process is pretty good. If I were to solve this problem, I would use
$callersand$ancestorswith Registry entry.And about GraphQL, I had a very similar problem and I just passed the user explicitly. Even if I have to pass it into 8 functions deep, I would just type 8 extra words, which is not a big deal, since explicit argument pays off in readability when compared to semi-global semi-mutable storage