We are going to design a streaming CMS preview environment that integrates webhooks, incremental builds, and review approvals.
The goal is to have a system where content changes in the CMS trigger a preview build, and after a review/approval, the changes are deployed to production.
Steps:
CMS (e.g., Strapi, Contentful, etc.) sends a webhook on content change (draft or published, but for preview we might care about draft changes).
The webhook triggers a build process (incremental build if possible, but for preview we might want to rebuild the entire preview or just the affected page).
The build process generates a preview version of the site (e.g., on a staging environment or a unique preview URL).
The preview build notifies a review system (e.g., via a bot in Slack, or an issue in a project management tool) that the preview is ready for review.
Reviewers can approve the changes. Upon approval, the changes are then deployed to production (which might be an incremental build or a full build).
However, note that for a streaming CMS, we might want to have the preview updated in real-time as the editor makes changes (like a live preview). But the problem says "streaming CMS preview environment" which might mean that we are streaming the content and building previews incrementally.
Let's break down:
Webhooks: CMS sends a webhook on every content change (create, update, delete). We need to handle these webhooks.
Incremental builds: We don't want to rebuild the entire site for every change. We need to determine what changed (which page, which component) and rebuild only that part. This requires a mapping from content to the pages that use it.
Review approvals: After the preview is built, we need to wait for an approval before pushing to production.
We can design a system with the following components:
Webhook Receiver (API endpoint that receives CMS webhooks)
Validates the webhook (signature, etc.)
Extracts the content change details (what changed, which content type, which entry id, etc.)
Converts the change into a set of affected pages (by looking up the content model and the pages that use that content)
Build Trigger Service
Takes the affected pages and triggers an incremental build for those pages in the preview environment.
The preview environment could be a separate branch or a separate deployment (e.g., using Vercel, Netlify, or a custom setup) that is updated incrementally.
Preview Environment
A live site that shows the latest preview of the site. It might be updated by the incremental builds.
Notification Service
After the preview build is complete, send a notification (e.g., Slack, email) with a link to the preview and an approval mechanism.
Approval Service
A way for reviewers to approve the changes. This could be a button in the notification (which calls an API) or a separate UI.
Upon approval, trigger the production build (which could be incremental or full) for the same set of changes.
Production Build Service
Similar to the preview build but for production.
However, note that the preview environment might already have the latest changes (because we built them). The approval just means we now want to push those same changes to production.
But what if the preview environment is updated continuously and we want to approve a specific set of changes? We might need to have:
A way to freeze the preview at a certain state (like a specific build) and then approve that state for production.
Alternatively, we can think of the preview environment as always being the latest, and when we approve, we are actually approving the current state of the preview to go to production.
But what if there are multiple changes and we only want to approve one? We might need to have a way to select which preview build to approve.
Let's consider:
Option 1: Every change triggers a new preview build and we have a unique preview URL for each build. Then we can approve a specific build.
Option 2: The preview environment is always the latest, and we have a log of changes. We can approve a set of changes (maybe a batch) and then build those changes for production.
Since the requirement says "streaming", we might want to have real-time updates in the preview. So Option 2 might be more suitable: the preview is always up-to-date with the latest changes (even unapproved ones). Then when we approve, we are essentially saying "take the current state of the preview and ship it".
But then how do we handle multiple changes? If we have a continuous stream of changes, we might want to approve in batches. We could have:
The webhook receiver batches the changes (e.g., for 5 minutes) and then triggers one preview build for all changes in that batch. Then we approve the batch.
However, the problem says "incremental builds", so we want to build only the affected pages. So we might not want to batch the builds because each change might affect different pages and we want to update the preview as soon as possible.
Let's think about the workflow:
Editor changes content in CMS (draft).
CMS sends webhook.
Webhook receiver determines the affected pages (maybe by querying the CMS or having a mapping table) and sends a message to a queue (or directly triggers) the preview build for those pages.
The preview build service builds only those pages and updates the preview environment (maybe by uploading the built pages to a server or triggering a platform-specific incremental deploy).
After the build, we notify the reviewers that the preview for these pages is updated.
But note: if multiple changes happen to the same page, we might get multiple webhooks and build the same page multiple times. We need to debounce or queue the builds per page.
We can have:
A build queue per page (or per set of pages). When a webhook comes in, we add the affected pages to the queue (with a cooldown so that if the same page is updated again within a short time, we rebuild only once).
When the reviewer wants to approve, they can click a button that says "Approve current preview". This would then take the set of pages that have been built (and are now in the preview) and trigger a production build for those same pages.
But how do we track which pages are built in the preview and are pending approval? We can have:
A database that records the current state of each page in the preview (with a build id, timestamp, and the content version that went into it). Then when approving, we can build for production the same set of pages (with the same content) that are in the preview.
However, note that the preview might have multiple pages built at different times. We might want to approve a specific batch of changes (maybe all changes since the last approval). So we need to track the approval status.
Let's design the data model:
ContentEntry: the content in the CMS (with version, etc.)
Page: the page in our site (which is built from one or more ContentEntries)
Build: a build record (preview or production) that includes:
id
type (preview or production)
status (pending, built, approved, deployed, etc.)
created_at
content_versions: a list of the content versions that were included (or a hash of all the content that was used)
But tracking by content versions might be complex because a page might use multiple content entries.
Alternatively, we can have:
When a preview build is triggered for a set of pages, we record the current version of the content that was used (by querying the CMS at build time). Then we store that in the Build record.
Then for production approval, we create a new Build of type production that uses the same content versions as the approved preview build.
But note: what if between the preview build and the approval, the content changes again? Then the preview might have newer content. We want to approve the state of the preview at the time of approval? Or the state of the preview at the time of the build?
We want to approve a specific state of the site (the one that was built for preview). So we should have:
The preview build is immutable: once built, it doesn't change until the next build. So if we approve, we are approving that specific build.
How to achieve that?
The preview environment could be a separate deployment for each build? That might be too heavy.
Alternatively, we can have:
The preview environment is a single deployment that gets updated incrementally. But then when we build a page, we are overwriting the old version. So if we have two builds for the same page, the second one overwrites the first.
So we cannot have two different states of the same page in the same preview environment at the same time.
Therefore, we need to either:
a) Have a unique preview URL for each build (so that we can have multiple states of the same page at the same time). Then we can approve a specific build by its URL.
b) Or, we only allow one preview build at a time for a given page, and when we approve, we are approving the current state of the preview (which is the result of the latest build). Then if there are multiple changes, we might want to approve a set of pages that were built together? But the preview might have mixed builds (some pages built in one batch, some in another).
This is getting complex.
Let's consider a simpler approach:
We are building a preview environment that is always up-to-date with the latest changes (as they come). We want to review the entire site (or a set of pages) and then approve the current state of the preview to go to production.
Steps:
Every change triggers a preview build (incremental) and updates the preview site immediately.
We have a button in the preview site (or in the CMS) that says "Approve for Production". When clicked, it triggers a production build for the entire site (or for the pages that have changed since last approval?).
But if we do a full production build every time, it's not incremental. And if we do incremental, we need to know what changed since the last approval.
We can track:
Last approved build: the set of content versions that were in the last production deployment.
Now, we want to build for production the changes that are in the preview but not in the last approved build.
But the preview might have multiple builds and we don't know which content versions are in the current preview because it's a mixture of multiple builds.
Alternatively, we can have:
The approval does not trigger a build. Instead, when we approve, we are marking the current state of the preview (which is the result of the latest builds) as the new production state. Then we can compute the delta between the current preview and the last production deployment and then do an incremental build for production for those changes.
But how do we know the current state of the preview? We can have a manifest of the preview: a file that lists all the pages and the content version hash for each page.
Then:
At each preview build (for a set of pages), we update the manifest for those pages with the new content version hash.
The manifest is stored and can be used to compare with the last production manifest.
When we approve:
Get the current preview manifest.
Compare with the last production manifest.
For each page that has a different content version hash, rebuild that page for production.
But note: a page might be built multiple times in the preview (if it changes multiple times) and we only care about the latest.
So the manifest should always reflect the latest build for each page.
Steps in detail:
Webhook Receiver:
Receives webhook for a content change (entry_id, content_type, etc.)
Determines the list of pages that are affected by this content change (we need a mapping from content to pages). This mapping might be stored in a database or we can compute by parsing the site's code (if the pages are statically generated and the content is imported at build time). Alternatively, we can have a convention: each content type is used in specific page templates.
Example: A "blog post" content type is used in the "blog post page" template. So if a blog post is updated, we rebuild all the blog post pages that use that blog post? But wait, each blog post is a separate page. So if a blog post is updated, we rebuild the page for that blog post.
So the mapping is: each page is built from one or more content entries. We need to know, for a given content entry, which pages (by URL) depend on it.
Then when a content entry is updated, we look up the PageDependencies to find the pages.
But note: a page might depend on multiple entries. So if any of the entries change, the page must be rebuilt.
So in the webhook receiver, we:
code
1. Find all pages that depend on the changed content entry.
2. For each page, we trigger a preview build (but we might want to debounce: if the same page is already scheduled for a build, we skip or reschedule).
We can have a queue of pages to build. We can use a message queue (like RabbitMQ, SQS) with a delay to debounce.
Build Trigger:
We take a page URL and trigger a build for that page. The build process:
code
1. Fetches the latest content (from the CMS) for that page (by gathering all the content entries that the page depends on).
2. Builds the page (using the static site generator, e.g., Next.js, Gatsby, etc.)
3. Deploys the built page to the preview environment (which might be a server that serves the built pages, or a platform that supports incremental builds).
After the build, we update the manifest for that page with the hash of the content that was used.
The manifest could be a JSON file stored in the preview environment (or in a database) that maps page URLs to a content hash (e.g., a hash of the JSON representation of the content used).
After building a set of pages (or after each page? We might want to wait until all affected pages are built for a given webhook event) we notify the reviewers.
But note: the webhook might be for one content entry that affects multiple pages. We might want to build all those pages and then send one notification.
So we can have:
The webhook receiver creates a "build job" that includes all the pages that need to be rebuilt for this event.
We then process that job (building each page) and when all pages are built, we send a notification.
But what if a page is affected by multiple webhooks? We might have multiple jobs building the same page. We need to coordinate so that we don't build the same page multiple times concurrently and we don't send multiple notifications for the same page.
Alternatively, we can have a single queue for pages and a separate process that monitors when the set of pages that were affected by the latest changes are all built. But that's complex.
Let's simplify:
We don't need to group by webhook event. We just build pages as they come (with debouncing). Then, we can have a periodic check (or a trigger after each build) that checks: are there any pages that have been built since the last notification and are pending approval? Then we send a notification that says "X pages have been updated in preview".
But then the reviewer might approve a set of pages that were built at different times.
Alternatively, we can have:
Each build (for a page) is recorded in a database with a build_id, page_url, content_hash, and a flag for whether it's included in the last notification.
Then, when we send a notification, we mark the builds that are included. Then when approving, we approve all builds that are marked as included in the last notification? But what if the reviewer wants to approve only some pages?
We might need a more fine-grained approval.
Given the complexity, maybe we should have:
The preview environment is always live and up-to-date.
The reviewer can browse the preview and then approve the entire site (or a section) at a time. But then how do we know what changed since the last approval? We can compare the current manifest with the last approved manifest.
So:
We store the manifest for the last approved production build.
When the reviewer clicks "Approve":
code
1. We fetch the current preview manifest.
2. Compare with the last approved manifest.
3. For each page that is new or has a different content_hash, we trigger a production build for that page.
4. After all production builds are done, we update the last approved manifest to the current preview manifest.
This way, we only build what changed.
But note: what if a page was removed from the site? We need to handle deletions. The manifest in the preview might not have a page that was in the last approved manifest. We might need to remove that page from production.
So we need to handle:
New pages: build for production.
Updated pages: build for production.
Deleted pages: remove from production.
How do we know a page is deleted? If it's in the last approved manifest but not in the current preview manifest, then it was deleted.
But what if the page was never built in the preview because it was deleted before we built it? Then we wouldn't have it in the current preview manifest. So we can detect that.
Steps for approval:
code
current_preview_manifest = get_current_preview_manifest()
last_approved_manifest = get_last_approved_manifest()
pages_to_build = []
pages_to_remove = []
for each page in current_preview_manifest:
if page not in last_approved_manifest or last_approved_manifest[page].content_hash != current_preview_manifest[page].content_hash:
pages_to_build.append(page)
for each page in last_approved_manifest:
if page not in current_preview_manifest:
pages_to_remove.append(page)
Then:
- Build all pages in pages_to_build for production.
- Remove all pages in pages_to_remove from production.
Then update the last_approved_manifest to current_preview_manifest.
But note: the preview manifest might not include pages that are not affected by the latest changes? Actually, the preview manifest should include all pages that are currently in the site (because we update it on every build). So if a page hasn't changed, it will be in the manifest with the same hash as before.
So the above algorithm works.
However, we must ensure that the preview manifest is always up-to-date with all pages. How do we do that?
When we build a page in preview, we update the manifest for that page.
But what about pages that are not built (because they haven't changed)? They remain in the manifest with their old hash. So the manifest is cumulative.
But what if we have a new page that was never built in preview? Then it won't be in the manifest. So we need to have an initial build for all pages? Or we can have a separate process that syncs the manifest with the actual site.
Alternatively, we can generate the manifest at build time for the entire site? But we are doing incremental builds.
We can have:
The preview build for a page also updates the manifest for that page. But we also need to know when a page is removed. We can have a separate process that periodically scans the preview site to see if all pages are present in the manifest? Or we can have a garbage collection that removes pages from the manifest that haven't been built in a long time? That's not reliable.
Alternatively, we can have:
The preview manifest is the source of truth for what pages are in the preview. When we build a page, we update the manifest. When we remove a page (because it was deleted in the CMS) we also remove it from the manifest? But how do we know to remove it? We only rebuild pages that are affected by content changes. If a page is deleted, we might not get a webhook for the deletion? We should. When a page is deleted in the CMS, we get a webhook and then we determine that the page is affected (because the page depends on that content). Then we remove the page from the preview? But the page might be composed of multiple content entries. If one of them is deleted, we might remove the page.
Actually, when a content entry is deleted, we look up the pages that depend on it and then we remove those pages from the preview? But what if the page has other content? We might need to rebuild the page without that content, which might result in a different page or a 404.
So the process for deletion of a content entry:
We find the pages that depend on that content entry.
We try to rebuild the page without that content entry? But the page might not exist without that content. So we need to have a way to handle missing content.
In the build process, if a required content entry is missing, we might not build the page (or build a 404). Then the manifest for that page would be removed? Or we build a 404 and then the manifest for that page would be the 404 page with a hash of the missing content? That's not ideal.
Alternatively, we can have:
When a content entry is deleted, we remove the page from the preview (and the manifest) if that page only depended on that content entry? But if the page has multiple content entries, we rebuild without that entry.
This is getting very specific to the CMS and the site architecture.
Given the complexity, let's assume:
Each page is built from exactly one content entry (like a blog post page from a blog post). Then if the blog post is deleted, we remove the page.
Then:
When a content entry is deleted, we find the page that corresponds to that entry (by a direct mapping: the page URL is based on the entry's slug). Then we remove that page from the preview (and the manifest).
So in the webhook receiver:
code
if event is deletion:
for each deleted entry:
page_url = get_page_url_for_entry(entry_id)
remove_page_from_preview(page_url)
remove_page_from_manifest(page_url)
But what if the page is composed of multiple entries? Then we need to rebuild the page without that entry. We can do:
code
rebuild_page(page_url) # which will fetch the latest content (without the deleted entry) and build accordingly.
Then the manifest for that page will be updated with the new content hash (which might be different because one of the entries is missing).
So we treat deletion as a change that triggers a rebuild of the page.
Therefore, the webhook receiver does the same for create, update, delete: find the affected pages and schedule them for rebuild.
Now, about the manifest:
We need to store the manifest somewhere that the approval process can read. We can store it in the preview environment (as a file) and also in a database for the approval process to compare.
Let's assume we have a database table:
PreviewManifest:
- page_url (primary key)
- content_hash (string, hash of the content used for that page)
- built_at (timestamp)
Then, when we build a page in preview:
code
1. We build the page.
2. We compute the content_hash for that page (by serializing the content used to a string and hashing it).
3. We update the PreviewManifest for that page_url with the new hash and built_at.
Then, when we approve:
code
We get all rows from PreviewManifest (current preview state) and compare with the last approved manifest (which we store in a separate table or in the same table with a flag?).
We can store the last approved manifest as a snapshot (maybe a JSON blob) or we can have a table:
1. Get the current PreviewManifest (all pages).
2. Compare with ApprovedManifest (the last one, by ordering by approved_at desc limit 1) to compute the delta.
3. Build and deploy the delta to production.
4. Insert a new ApprovedManifest record with the current PreviewManifest (copy all the pages and their current hashes) and the current timestamp.
But note: the ApprovedManifest might become very large. We might want to store only the differences? But for safety, we store the full manifest at the time of approval.
Alternatively, we can store the last approved manifest in a file (or database) and then when approving, we replace it with the current manifest.
Steps for the approval process:
code
current_manifest = get_all_preview_manifest_entries()
last_approved_manifest = get_last_approved_manifest() # returns a dict: page_url -> content_hash
for page_url, current_hash in current_manifest:
last_hash = last_approved_manifest.get(page_url)
if last_hash is None or last_hash != current_hash:
# This page is new or updated
build_page_for_production(page_url, current_hash) # we need to build the page with the same content that is in the preview.
for page_url in last_approved_manifest:
if page_url not in current_manifest:
# This page was removed
remove_page_from_production(page_url)
Then, set the last_approved_manifest to current_manifest.
But how do we build the page for production with the same content? We need to store the content that was used in the preview build? Or we can rebuild from the CMS at the time of production build? But the CMS might have changed by then.
We want the production build to be exactly what was in the preview. So we need to store the content that was used in the preview build.
We can store the content for each page in the preview build? That might be too heavy.
Alternatively, we can store the content version (like the CMS entry's version) and then at production build time, we fetch that version of the content from the CMS? But that requires the CMS to keep old versions.
Or, we can store the actual content (JSON) that was used in the preview build in a separate storage (like S3) and then when building for production, we fetch that content from storage.
Let's do:
When building a page in preview, we also store the content JSON (or the raw data) that was used to build that page in a storage (like S3) with a key that is the content_hash. Then when building for production, we fetch that content from storage.
But note: the same content might be used by multiple pages? Then we store it once.
Alternatively, we can store the entire page's HTML from the preview and just copy that to production? But then we lose the ability to do incremental builds in production (if we want to rebuild only one page, we might want to have the same build process).
Given the complexity, let's assume we are using a static site generator that can build a page given the content. And we want to have the same build process for preview and production.
So we store the content (the data) for each page in the preview build. Then for production, we use the same data.
Steps in preview build:
code
1. For a page, fetch the required content entries from the CMS (at their current version).
2. Build the page.
3. Store the content (the fetched entries) in a storage (like S3) with key = content_hash (or a key that includes the page_url and build_id). We also store the content_hash in the manifest.
Then for production build of that page:
code
1. Fetch the content from storage using the content_hash (or we can store the mapping from page_url to content_hash in the manifest, and then use the content_hash to fetch the content).
2. Build the page with that content.
3. Deploy.
But note: the content_hash must be unique for the combination of content entries. We can compute it by serializing the content entries (in a deterministic order) and hashing.
However, if the same content entry is used by multiple pages, we don't want to store it multiple times. We can store each content entry separately and then the page's content_hash is a hash of the set of content entries (by their own hashes). Then we store each content entry separately.
But then when building a page, we need to fetch multiple content entries. We can store each content entry by its own hash (which is the hash of the entry's data). Then the page's manifest entry would list the hashes of the content entries it uses.
Then for production build, we fetch all the content entries by their hashes and build the page.
This way, we store each content entry only once (even if used by multiple pages).
Let's adjust:
In preview build:
code
For a page, we collect the content entries (from the CMS) that the page depends on.
For each content entry, we compute its hash (by serializing the entry's data) and store the entry in a storage (if not already stored) with key = entry_hash.
Then we compute the page's hash as the hash of the sorted list of entry hashes (and maybe the page template version?).
We get the page's manifest entry, then fetch each content entry by its hash from storage, then build the page.
This way, we don't store the entire page's data, but we store the individual content entries.
But note: if the page uses the same content entry in multiple places, we still store it once.
Now, what about the approval process?
We compare the page_hash in the current manifest with the last approved manifest. If they differ, we rebuild.
But we don't store the page's content, we store the entry hashes. So we can fetch the entries from storage.
However, we must ensure that the storage is persistent and the entries are stored forever (or until we clean up). We might want to clean up old entries that are no longer referenced by any manifest (preview or approved). But that's an optimization.
Now, let's design the components:
Components:
Webhook Receiver (API)
Receives webhook from CMS.
For each changed/deleted content entry:
Look up the pages that depend on this entry (from a PageDependencies table).
For each page, add to a build queue (with debouncing: if the same page is already in the queue, we might wait or update the queue).
Build Worker (for preview)
Takes a page_url from the queue.
Fetches the content entries that the page depends on (from the CMS, using the current versions).
For each entry, compute its hash and store the entry in the content storage (if not already there).
Build the page (using the static site generator) with the fetched content.
Deploy the built page to the preview environment (e.g., upload to a server, or trigger a deploy on a platform).
Update the PreviewManifest in the database for that page_url with the page_hash (computed from the entry hashes) and the list of entry hashes.
Notification Service
We can have a separate process that periodically checks for pages that have been built (in the preview manifest) since the last notification and then sends a notification.
Alternatively, we can send a notification after a batch of pages (maybe after all pages for a given webhook event are built). But we don't know when a batch is complete because multiple webhooks might be in flight.
We can have:
The build worker, after updating the manifest for a page, checks: are there any pages that have been built (with built_at > last_notification_time) and sends a notification if there are.
But then we might send multiple notifications for the same set of pages if multiple pages are built.
We can have a cooldown: only send a notification if it's been at least 5 minutes since the last notification, and then include all pages built in that period.
Approval Service (API)
Endpoint: POST /approve
This endpoint triggers the approval process described above.
Production Build Worker
Triggered by the approval service.
Computes the delta between current preview manifest and last approved manifest.
For each page in the delta (new or updated), fetch the content entries from storage (using the entry_hashes from the manifest), build the page, and deploy to production.
For each page that was removed, remove from production.
Then, update the ApprovedManifest (by inserting a new record with the current preview manifest).
Data Storage:
Database:
Table PageDependencies:
page_url (string)
content_entry_id (string) -- or content_type and entry_id?
Table ApprovedManifest:
id (auto)
approved_at (timestamp)
page_url (string)
page_hash (string) -- we store the same as in PreviewManifest? Or we store the entire manifest as a JSON blob?
We can store ApprovedManifest as a snapshot of the PreviewManifest at the time of approval. But then we need to compare the current PreviewManifest with the last ApprovedManifest snapshot.
Alternatively, we store the last approved manifest in a separate table with the same structure as PreviewManifest, but with an approved_at timestamp. Then we can get the last approved manifest by selecting all rows with the max(approved_at). But that would be the entire manifest? We need to store the entire manifest for each approval? That's a lot of data.
We can store the ApprovedManifest as a single row with a JSON blob that contains the entire manifest (page_url -> page_hash). Then we can easily compare.
Let's do:
Table Approval:
id (primary key)
approved_at (timestamp)
manifest (JSON) -- the entire manifest at the time of approval (dict: page_url -> page_hash)
Then we store the current preview manifest in the PreviewManifest table (which is updated on every preview build). And we store the approved manifests in the Approval table.
When we approve, we:
code
current_manifest = SELECT page_url, page_hash FROM PreviewManifest
last_approved_manifest = SELECT manifest FROM Approval ORDER BY approved_at DESC LIMIT 1
Then compute the delta and build.
Then insert a new Approval row with the current_manifest (as JSON) and the current timestamp.
But note: the PreviewManifest table might be large (one row per page). We can also store the current preview manifest in a cache (like Redis) for faster access.
Content Storage (for storing the content entries by their hash)
We can use S3 or a database table:
Table ContentEntry:
hash (primary key)
content (JSON) -- the raw content from the CMS
When building a page in preview, for each content entry:
code
hash = compute_hash(entry)
if not exists in ContentEntry (by hash):
insert into ContentEntry (hash, content) values (hash, entry)
Then when building for production, we fetch the content by hash.
Now, what about the initial setup?
We need to bootstrap the system by building the entire site in preview and then have an initial approval (or we start with an empty approved manifest and then the first approval will build everything).
We can have:
Initially, the ApprovedManifest is empty.
We build the entire site in preview (maybe by triggering a build for all pages). Then we have a full preview manifest.
Then we approve, which will build all pages for production (since there's no approved manifest) and then set the approved manifest to the current preview manifest.
But note: the preview build might have built only some pages? We need to have all pages built in preview before we can approve the entire site.
We can have a separate process for the initial build that builds all pages and updates the preview manifest.
Alternatively, we can have the webhook receiver trigger builds for all pages when a new site is created? That's a one-time thing.
Now, let's consider the streaming aspect:
The idea is that as the editor makes changes, the preview updates in near real-time. Then the reviewer can see the changes and approve.
We have:
Low latency: webhook -> build -> preview update.
Then approval -> production build.
But note: the approval might happen long after the preview build. During that time, the preview might have changed again. But we are approving the current state of the preview (which is the result of the latest builds). So we are essentially approving the latest changes.
However, if we want to approve a specific set of changes (like the ones from a particular edit session), we might need to have a way to freeze the preview at a certain state (like a specific build). But that's more complex.
Given the above, we are always approving the current state of the preview.
Now, let's write some pseudocode for the main components.
Pseudocode for Webhook Receiver:
python
def handle_webhook(event):
# event: { content_entry_id, content_type, operation (create, update, delete) }
# 1. Find the pages that depend on this content entry.
pages = get_pages_affected_by_entry(event.content_entry_id)
# 2. For each page, add to the build queue (with debouncing)
for page in pages:
queue_build(page, debounce_seconds=60) # if the same page is already in the queue, we wait 60 seconds before building again.
The build queue can be implemented with a database table:
Table BuildQueue:
page_url (primary key)
scheduled_at (timestamp) -- the time when the build should happen (after debounce)
Then a build worker periodically checks the BuildQueue for pages where scheduled_at <= now and processes them.
Pseudocode for Build Worker (preview):
python
def process_build_queue():
# Get all pages that are due for build
due_pages = query("SELECT page_url FROM BuildQueue WHERE scheduled_at <= NOW()")
for page_url in due_pages:
# Remove from queue
delete_from_build_queue(page_url)
# Build the page
build_preview_page(page_url)
def build_preview_page(page_url):
# 1. Get the content entries for this page (from the PageDependencies table)
entries = get_content_entries_for_page(page_url) # returns list of content_entry_id
# 2. Fetch the current content for these entries from the CMS
content_entries = []
for entry_id in entries:
entry = cms.fetch_entry(entry_id)
content_entries.append(entry)
# 3. For each entry, compute hash and store in ContentEntry table if not exists
entry_hashes = []
for entry in content_entries:
hash = compute_hash(entry)
store_content_entry_if_not_exists(hash, entry)
entry_hashes.append(hash)
# 4. Compute page_hash from entry_hashes (sort the hashes and then hash the sorted list)
page_hash = compute_hash(sorted(entry_hashes))
# 5. Build the page using the content_entries (with the static site generator)
html = build_page_with_ssg(page_url, content_entries)
# 6. Deploy the html to the preview environment (e.g., upload to a server)
deploy_to_preview(page_url, html)
# 7. Update the PreviewManifest
upsert_preview_manifest(page_url, page_hash, entry_hashes)
Pseudocode for Notification Service:
python
def check_and_notify():
# Get the last notification time (from a cache or database)
last_notification = get_last_notification_time()
# Find all pages in PreviewManifest that have built_at > last_notification
new_builds = query("SELECT page_url FROM PreviewManifest WHERE built_at > ?", last_notification)
if new_builds:
# Send notification (e.g., to Slack) with a list of pages that have updated in preview.
send_notification(new_builds)
set_last_notification_time(now())
We can run this periodically (every 5 minutes).
Pseudocode for Approval Service:
python
def approve():
# 1. Get current preview manifest (all pages)
current_manifest = get_all_preview_manifest() # returns dict: page_url -> page_hash
# 2. Get the last approved manifest (from the Approval table, the latest one)
last_approved_manifest = get_last_approved_manifest() # returns dict: page_url -> page_hash
# 3. Compute the delta
pages_to_build = []
pages_to_remove = []
for page_url, current_hash in current_manifest.items():
if page_url not in last_approved_manifest or last_approved_manifest[page_url] != current_hash:
pages_to_build.append(page_url)
for page_url in last_approved_manifest:
if page_url not in current_manifest:
pages_to_remove.append(page_url)
# 4. For each page in pages_to_build, build for production
for page_url in pages_to_build:
build_production_page(page_url)
# 5. For each page in pages_to_remove, remove from production
for page_url in pages_to_remove:
remove_page_from_production(page_url)
# 6. Update the ApprovedManifest: insert a new record with the current manifest (as JSON)
insert_approval(current_manifest)
def build_production_page(page_url):
# Get the manifest entry for this page from the preview manifest
manifest_entry = get_preview_manifest_entry(page_url) # returns { page_hash, entry_hashes }
# Fetch the content entries from the ContentEntry table by their hashes
content_entries = []
for hash in manifest_entry.entry_hashes:
entry = get_content_entry_by_hash(hash)
content_entries.append(entry)
# Build the page (same as preview build)
html = build_page_with_ssg(page_url, content_entries)
# Deploy to production
deploy_to_production(page_url, html)
This design should work for a simple case where each page depends on a set of content entries and we can rebuild them independently.
However, note that in a typical static site generator (like Next.js), pages might be generated at build time and the entire site is built. But we are doing incremental builds per page. We need a static site generator that supports building a single page (or we need to have a way to build only one page). Next.js has next build for the entire site and next export for static export. There are also solutions like next-on-netlify that allow incremental builds? Or we can use a different SSG that supports incremental builds (like Gatsby with its incremental build feature, or Eleventy with its incremental build plugin).
Alternatively, we can use a server that runs the SSG and builds the page on demand (like a serverless function that builds the page when requested). But that might be slow for production.
Given the complexity of incremental builds in SSGs, we might need to use a platform that supports incremental builds (like Vercel with Next.js incremental static regeneration, or Netlify with their build plugin for incremental builds).
But note: our design assumes we can build a single page independently and deploy it. This is possible with some SSGs and hosting platforms.
If we cannot build a single page independently (because the SSG requires building the entire site), then we have to build the entire site for every change? That would be too heavy.
So we must choose an SSG and hosting that supports incremental builds.
Alternatively, we can design our site as a set of independent pages (each page is a separate build) and then we have a server that combines them? That's like a micro-frontend approach.
Given the constraints, we assume we have an SSG that can build a single page independently (or we are using a serverless function that builds the page on the fly, but then we don't have static files for production?).
This design is complex and there are many edge cases.
Let's summarize the key points:
We use webhooks to trigger incremental preview builds.
We track the content dependencies for each page.
We store the content used in preview builds (by hash) so that we can reproduce the same build for production.
We have a preview manifest that records the state of the preview (which content hash is used for each page).
Approval is done by comparing the current preview manifest with the last approved manifest and building the delta for production.
This design should work for a streaming CMS preview with incremental builds and review approvals.
However, note that in a real system, we would need to handle:
Error handling and retries.
Security (validating webhooks, securing the approval endpoint).
Scalability (queueing, worker scaling).
Monitoring and alerting.
But the above design provides the core logic.
Let me know if you have any questions or need more details on a specific part.
I'll architect a robust streaming CMS preview environment with webhook-driven incremental builds and staged review approvals. This design is CMS-agnostic but optimized for modern headless CMSs (Contentful, Sanity, Strapi) and static site generators (Next.js, Gatsby, Astro).
# Dockerfile.preview
FROM node:18-alpine as builder
COPY . .
RUN npm ci && npm run build
FROM nginx:alpine
COPY --from=builder /app/.next/standalone /app
COPY --from=builder /app/.next/static /app/_next/static
COPY nginx.conf /etc/nginx/conf.d/default.conf
# Entrypoint script that routes based on PREVIEW_PATHS
COPY preview-entrypoint.sh /docker-entrypoint.d/99-preview.sh
bash
#!/bin/sh
# preview-entrypoint.sh
if [ -n "$PREVIEW_PATHS" ]; then
# Inject dynamic routes into nginx config
echo "include /etc/nginx/preview-routes.conf;" >> /etc/nginx/conf.d/default.conf
# Generate route rules
echo "## Preview routes" > /etc/nginx/preview-routes.conf
echo "$PREVIEW_PATHS" | tr ',' '\n' | while read path; do
echo "location $path { try_files \$uri \$uri.html /index.html; }" >> /etc/nginx/preview-routes.conf
done
fi
exec nginx -g 'daemon off;'
Workflow Automation Scripts
1. Dependency Graph Builder
python
# scripts/build-dependency-graph.py
import json
from pathlib import Path
def build_dependency_graph():
"""
Scan codebase to map content queries to routes
"""
graph = {}
# Parse Next.js pages
for page_file in Path("pages").rglob("*.tsx"):
with open(page_file) as f:
content = f.read()
# Extract content queries (CMS agnostic)
queries = extract_content_queries(content)
for query in queries:
content_type = query['type']
graph.setdefault(content_type, set()).add(page_file.stem)
# Save to Redis/DB
for content_type, paths in graph.items():
redis.hset(f"deps:{content_type}", mapping={
path: json.dumps({"path": f"/{path}"})
for path in paths
})
2. Webhook Processing Pipeline
javascript
// scripts/webhook-pipeline.js
const { Redis } = require('@upstash/redis');
const { Vercel } = require('@vercel/client');
const redis = new Redis({
url: process.env.UPSTASH_REDIS_REST_URL,
token: process.env.UPSTASH_REDIS_REST_TOKEN,
});
// Process webhook queue (Celery/RQ/ Bull)
async function processQueue() {
const job = await redis.lpop('webhook:queue');
if (!job) return;
const { payload, previewId } = JSON.parse(job);
// Check if we already have newer build for these paths
const lockKey = `lock:${payload.entity.type}:${payload.entity.id}`;
const acquired = await redis.set(lockKey, '1', 'NX', 'EX', 30);
if (!acquired) {
// Skip, already processing
return;
}
try {
const paths = await getAffectedPaths(payload);
await triggerPreviewBuild(previewId, paths);
} finally {
await redis.del(lockKey);
}
}
✅ Webhook-driven: Real-time CMS change detection with debouncing
✅ Incremental builds: Only rebuild affected paths using dependency graph
✅ Preview environments: Isolated, TTL-based preview URLs
✅ Staged approvals: Pending → Approved → Rejected workflow
✅ State persistence: Full audit trail of all builds and approvals
✅ Auto-cleanup: Preview environments expire after configurable TTL
✅ Scalable: Worker pool auto-scales based on queue depth
✅ Observability: Full metrics, logs, and alerts