The beauty of Firebase triggers

David Dikman
May 12 · 4 min read

Even if you are not using Firebase, bear with me.

This is still applicable for any microservices or when using NoSQL or other types of de-normalized data.

Before we get into it, let me explain what I mean with some of those terms:

  • With denormalized data, I refer to data that is not in 3rd normal form. Data that is duplicated across stored entries. An example could be saving an author name in both an article and the user object.
  • Microservices is a way of splitting our application into separate runnable pieces that are independently deployable. This can help make some things easier such as updating, scaling and maintaining the code. However, it also comes at a cost of complexity.
  • A monolith is an opposite of using microservices. All functionality runs inside a single deployable application.
  • NoSQL databases require different approaches to multi-row updates compared to SQL databases where we simply run a update to update a large number of entries

With that cleared up, let us talk about what triggers are.

How traditional triggers work

The type of trigger I will talk about today is something that causes some code to run when something changes.

First, let us look at how common ORM frameworks does this. Examples can be Microsoft’s EntityFramework, Hibernate or the example I’ll use here, Active Record for Rails. Though the syntax and features for each ORM are different usually they have the same core capabilities for listening to changes.

In Active Record specifically, we use callbacks to react to changes in models (aka database tables). The model inherits a base class that provides helper functions that we can use to register callbacks. In these callbacks, we can then run code when the model changes.

Diagram of a common Active Records event model in Rails
class User < ActiveRecord::Base  after_create    :subscribe_mailing_list, :send_welcome_mail

The ActiveRecord triggers make it very simple to react to data changes. They require very little code, for example to, trigger an email when a user is saved.

The drawback is that this trigger code has to be inside the model itself. That model then needs to depend on whatever functionality we want to happen.

This is, of course, avoidable. We can for example decouple it with Pub/Sub but out of the box, this and similar patterns often lead to big bloated models which become harder and harder to test and maintain.

How Firebase triggers work

Exactly how Firebase triggers work I can’t vouch for but I think they are built on the Google Pub/Subsystem which is an async message system used to decouple and scale complex systems.

It wraps the message system behind the Cloud Functions SDK so you don’t have to worry about the details. It gives you these two big benefits:

  1. All default services provide events you can listen to without adding any additional logic on your side
  2. It is naturally distributed and scalable, the functions will scale up to run as many as are needed, queued etc

You actually register your cloud functions to be called on certain events so all code has a trigger as their endpoint, for example:

exports = module.exports = functions.auth.user().onCreate(async (user) => {  await initUser(user.uid);});

Naturally extendible

The beauty of message-based architectures is the way they are naturally decoupled making them very extensible.

Each service (Firestore, Auth etc) exposes low-level key events and whenever and wherever you need, you can hook into these to execute some code without having to modify the source service.

Where would we use this? It is actually perfect for core business logic, for example:

  • When an order is cancelled do a refund
  • When a user has done a specific conversion event, send them an email
  • When a new item is saved, save denormalized data for more performant reading

Not just Firebase

Of course, using message-based systems and raising events is nothing new. With modern tools, you can also easily use this in your architecture. There is Google Pub/Sub or AWS Lamba.

What you need to do though is to prepare your architecture with a Framework that allows you to do two things simply:

  1. Raise generic events for your services. This way, as you add functionality the base events should support new types of data being added without having to manually hard code raising events for these. An example is, instead of raising an event when saving the User model, raise an event on saving any model, passing in the modal as a JSON object.
  2. Create a generic framework for easily subscribing to these events. That way the friction of extending functionality by subscription will be lower than to be tempted to add the functionality close to where the event is raised

With these two things, you’ve achieved what Firebase gives out of the box.

Firestore triggers and an example of de-normalized models

Below is an actual example that updates the author name in all the author’s articles when the author changes name. A function listens to changes in the user object and then updates the articles if the name is what has changed.

Check out the docs

As a wrap-up, show all the Firebase events, link to the documentation and ask people to give their thoughts.

For a full list and documentation see the Firebase cloud functions documentation.

Nerd For Tech

From Confusion to Clarification

David Dikman

Written by

Active reader, developer, manager, entrepreneur & sporadic writer here and at https://greycastle.se. Currently working at https://styler.link.

Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/. Don’t forget to check out Ask-NFT, a mentorship ecosystem we’ve started

David Dikman

Written by

Active reader, developer, manager, entrepreneur & sporadic writer here and at https://greycastle.se. Currently working at https://styler.link.

Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/. Don’t forget to check out Ask-NFT, a mentorship ecosystem we’ve started

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store