# Reviving My 🦋 Bluesky Topic Trends App with Gemini Decision 1, Antigravity, and Cloud Run

> How I turned a one-shot Bluesky firehose script into a real-time multi-language trend viewer on Cloud Run, using gemini-decision-1 for NSFW filtering and language reassignment, plus a 40x+ clustering speedup built with Antigravity's /swarm and /boost.

Author: [Guillaume Laforge](https://glaforge.dev/) | Published: 2026-12-04 | Topics: bluesky, gemini, generative-ai, antigravity, cloud-run, clustering, visualization, langchain4j, java, micronaut | Canonical: https://glaforge.dev/posts/2026/12/04/reviving-bluesky-topic-trends-with-gemini-decision-1-antigravity-and-cloud-run/


Almost two years ago, I wrote an article on [analyzing trends and topics from 🦋 Bluesky's Firehose with generative AI](https://glaforge.dev/posts/2025/01/06/analyzing-trends-and-topics-from-blueskys-firehose-with-generative-ai/).
At the time, it was a straightforward local script: connect to Bluesky's [Jetstream](https://github.com/bluesky-social/jetstream) WebSocket, accumulate 10,000 English posts, run a single batch pass of embeddings, cluster them, ask Gemini for short labels, and dump a static JavaScript file to render one [D3.js](https://d3js.org/) bubble chart.

It worked for a demo, but the snapshot froze the moment the script exited.
This week, I revived that project with [Google Antigravity](https://antigravity.google/) and **Gemini 4 Neon** and turned it into a hosted, real-time, multi-language trend viewer running on Google Cloud Run.

> [!NOTE]
> **Try it live right now:**
> - :uk: **English trends:** [bsky-topics.cloud.run/?lang=en](https://bsky-topics.cloud.run/?lang=en)
> - :fr: **French trends:** [bsky-topics.cloud.run/?lang=fr](https://bsky-topics.cloud.run/?lang=fr)
> - :computer: **Source code:** [github.com/glaforge/bluesky-topic-analysis](https://github.com/glaforge/bluesky-topic-analysis)

> [!WARNING]
> If nobody has been watching a language for 30 seconds, the app enters \$0/hr idle standby and only buffers raw posts. Give it 10–15 seconds to wake up, filter, and embed the rolling window when you open a tab!

## From a One-Shot Script to a Real-Time Cloud Run App

The original 2025 prototype was a batch pipeline: 
- accumulate posts until a counter hits a target, 
- process everything once, 
- write a file to disk, 
- and stop.

To make it genuinely useful as a live trends dashboard, the architecture had to shift to continuous streaming.

The revived version runs on [**Micronaut 5**](https://micronaut.io/) and **Java 25**, deployed to [**Cloud Run**](https://cloud.run/) directly from a self-contained fat JAR (no Dockerfile needed) behind the `bsky-topics.cloud.run` vanity URL.
Instead of a one-time pass, it maintains a continuous Jetstream WebSocket connection with cursor-based resume and feeds parallel 4,000-post rolling windows (currently **English** and **French** by default, and with more languages toggleable live from a protected admin console).

Every ~30 seconds, each active language window is reclustered, matched against previous snapshots to preserve persistent topic IDs and rank history, enriched with extra signals (author diversity, cluster tightness, mood, arrival histograms, 
and 2D [PCA](https://en.wikipedia.org/wiki/Principal_component_analysis) coordinates), and pushed to connected browsers over **Server-Sent Events (SSE)**.
When no viewer is connected to a language stream, all Gemini API calls pause completely while raw posts keep accumulating in memory for free.

![Architecture evolution from 2025 one-shot batch script to 2026 Cloud Run real-time streaming app](/img/bluesky/revival-architecture-before-after.svg)

## The Model Upgrade: Introducing `gemini-decision-1`

The 2025 version relied on two Vertex AI models: `text-embedding-005` (128 dimensions) for embeddings and `gemini-1.5-flash-002` for short cluster titles.
Any post that arrived with the right language tag went straight into the embedding model, which had two annoying side effects on real social media traffic:

1. **NSFW and adult spam clusters**: spam accounts and adult promo rings post repetitive text at high volume, so density-based clustering eagerly groups them into prominent bubbles.
2. **Badly labeled spoken languages**: plenty of Bluesky users leave their app's default posting language set to English while writing in French (or vice-versa). Naive tag filtering either lets English posts pollute the French clusters, or forces you to drop valid posts entirely.

In the revived app, I moved to a three-model pipeline on the Gemini API via [LangChain4j](https://docs.langchain4j.dev/):

- **`gemini-decision-1`** up front as a fast, low-cost gatekeeper before embedding.
- **`gemini-embedding-001`** (256-dim [Matryoshka](https://huggingface.co/blog/matryoshka) vectors with the `CLUSTERING` task type), which also gives us a shared multilingual embedding space across languages.
- **`gemini-4-hydrogen`** (with low thinking) to generate concise topic labels alongside an inline mood classification (`Breaking`, `Heated`, `Playful`, `Informative`, or `Celebratory`), cached across refreshes until a cluster's membership changes significantly.

![AI model stack before and after: 2 Vertex AI models vs. 3 specialized Gemini models](/img/bluesky/revival-models-before-after.svg)

### What `gemini-decision-1` Enables in Practice

I recently wrote about using `gemini-decision-1` for [multimodal decisions](https://glaforge.dev/posts/2026/11/13/multimodal-decisions-with-gemini-decision-1-and-the-interactions-java-sdk/) and [RAG reranking](https://glaforge.dev/posts/2026/11/30/reranking-rag-results-with-gemini-decision-1-and-langchain4j/).
Here, it solves both the NSFW problem and the mislabeled-language problem in a single pass.

Because `gemini-decision-1` emits **zero output tokens** and is billed at **\$0.10 per 1M input tokens**, we pack up to **50 posts** into a single batched decision request and attach two questions per post on the exact same shared input text (so we never pay twice to send the post text):

1. **NSFW & harassment spam check** (yes/no question): flags adult promotion, explicit content, and sexual harassment spam before those posts ever reach the embedding model or the UI.
2. **Spoken language identification & reassignment** (multi-choice question): when multiple language streams are active (like `en` and `fr`), the model classifies each post's actual written language across the active streams plus `other`. If a clean post tagged as French is actually written in English, it is not discarded: it gets **reassigned directly into the English rolling window** (and vice-versa, as well as for other language pairs).

> [!IDEA] 
> One neat edge case came up during live testing: occasionally a batch of 50 posts contains a single post severe enough to trigger Gemini's upstream safety filter for the whole request.
> Rather than dropping all 50 posts (or letting the offending one slip through), the pipeline **recursively bisects** any safety-blocked batch into halves until it isolates and drops only the exact offending post(s), while keeping every clean post in the batch.

## Six Live D3.js Visualizations

The original app had a single static bubble chart.
Now that we have rolling windows, persistent topic tracking, 256-dim multilingual centroids, and 60 snapshots of live history, the web UI exposes **six interactive D3.js views** that all update live over SSE and share the same search filter and **Topic Explorer** drawer.

### 1. Bubbles + Live Signal Encodings & Topic Explorer

The default view is still a circle-packed bubble chart, now inertia-anchored so bubbles do not jump wildly across the screen on every 30-second update.
At the top, a **Color by** toggle lets you re-encode the same clusters on the fly across five signals: **Volume**, **Trend**, **Diversity** (unique authors ratio, useful for spotting bot rings), **Tightness** (how semantically focused the cluster is), and **Mood**.

Clicking any bubble opens the **Topic Explorer** drawer on the right with post volume, trend delta, diversity, tightness, mood, extracted keywords, and clickable representative posts linking directly to Bluesky.

![Bubbles view sized and colored by post volume](/img/bluesky/revival-bubbles-volume.png)

### 2. Cross-Language Bridges (English ↔ French)

Because `gemini-embedding-001` embeds all language posts into the same 256-dimensional vector space, we can compute cosine similarity directly across all language topic centroids without translating a single post.

The **Cross-Lang Bridges** view puts one language topics on the left and another language topics on the right, drawing gradient ribbons between global stories discussed in both languages while dimming local-only conversations.
You can slide the match strength threshold (default 80%) or hide local-only clusters to focus purely on shared international topics.

![Cross-Language Bridges linking shared English and French topics with gradient ribbons](/img/bluesky/revival-cross-lang-bridges.png)

### 3. Semantic Galaxy

The **Semantic Galaxy** projects all clustered posts in the rolling window onto the top 2 principal components (computed server-side in a few milliseconds) and wraps them in glowing topographic density contours.

Topics that are semantically close sit near each other on the map, while isolated niches form their own islands.
You can scroll to zoom, drag to pan (your viewport stays put across live SSE refreshes), and click any highlighted star to preview the actual post text.

![Semantic Galaxy 2D PCA starfield with topographic density contours](/img/bluesky/revival-semantic-galaxy.png)

### 4. Streamgraph & Rank Bump Chart

Keeping persistent topic IDs across refreshes unlocks time-series views over a rolling history of up to 60 live snapshots.
The **Stream & Bump** tab lets you switch between a **Streamgraph** (flowing volume ribbons showing stories rising and receding over time) and a **Rank Bump** chart tracking top-10 rank climbs and drops.

![Trends Over Time streamgraph tracking 60 live snapshots](/img/bluesky/revival-streamgraph.png)

### 5. Heartbeat Waves (Joyplot)

Two clusters with 60 posts can behave very differently: one might be steady background chatter spread over 30 minutes, while another might be a breaking news spike from the last two minutes.

**Heartbeat Waves** plots smoothed 24-bin post arrival histograms across the rolling window, colored from cool green (steady chatter) to dark red (spiking right at the live edge).
Sorting by **Most Bursty** immediately surfaces stories that are breaking right now.

![Heartbeat Waves ridgeline plot showing bursty breaking spikes vs. steady chatter](/img/bluesky/revival-heartbeat-waves.png)

### 6. Momentum Quadrant

Finally, the **Momentum Quadrant** plots each topic's age (minutes since it first appeared) against its recent post change (or relative growth rate).
This splits the firehose into four actionable zones: 
- **Breaking / Viral** (young and surging), 
- **Sustained Trends** (older and still growing), 
- **Niche Flashes** (young and settling), and 
- **Cooling Down** (older and fading).

![Momentum Quadrant separating breaking viral stories from sustained trends and cooling topics](/img/bluesky/revival-momentum-quadrant.png)

## Building with Antigravity: `/swarm` and `/boost`

Reviving this project was also a great test of two Google Antigravity workflows powered by **Gemini 4 Neon**: `/swarm` and `/boost`.

### Parallelizing the Rewrite with `/swarm`

Turning a single-file CLI script into a full-stack streaming web application involves a lot of independent surface area: Micronaut SSE plumbing, the `gemini-decision-1` batch filter, persistent topic tracking, six distinct D3.js views, an admin console with live cost tracking, and Cloud Run deployment hardening.

As I described in my previous post on [Antigravity Swarms](https://glaforge.dev/posts/2026/11/25/seeing-what-your-coding-agents-are-doing-antigravity-swarms-and-generative-ui/), invoking [`/swarm`](https://antigravity.google/docs/swarm/) turns the conversation into a coordinator that splits independent tracks across parallel worker agents sharing a message board, alongside a dedicated verifier agent running builds and tests.
Instead of grinding through frontend views, backend endpoints, and Cloud Run probes sequentially in one long thread, multiple workers built and verified their pieces concurrently while staying out of each other's files.

### Landing the Clustering Breakthrough with `/boost`

While `/swarm` shines for parallel feature delivery, the hardest technical bottleneck in this revival was a single deep algorithmic problem: **DBSCAN clustering was too slow for a live rolling window, and raw embeddings were collapsing unrelated topics into one giant catch-all bubble**.

That is where Antigravity's [**`/boost`**](https://antigravity.google/docs/boost/) slash command made the difference.
`/boost` pushes the agent into deep thinking, strategic planning, multiple perspectives, and rigorous verification.
Running `/boost` with **Gemini 4 Neon** on the clustering bottleneck led to both a mathematically exact **40×–60× speedup** and a clean fix for topic collapse, backed by offline parity tests proving 100% identical cluster assignments against Apache Commons Math.

## How Gemini 4 Neon Sped Up Clustering by 40×–60×

> [!WARNING]
> My math is pretty rusty, so I asked Antigravity & Neon to come up with the below explanation of the clustering algorithm re-implementation.
> Hold tight, or feel free to skip the maths! 
> Sorry in advance, but I don't provide painkillers for the headaches caused!

In the 2025 prototype, I used Apache Commons Math's standard [DBSCAN](https://en.wikipedia.org/wiki/DBSCAN) implementation.
It is easy to call, but it does single-threaded, brute-force $O(N^2)$ distance checks over boxed Java objects, evaluating every pair $(i, j)$ twice and computing a square root on every comparison.
At 4,000 posts, a single clustering pass took **1.1 to 1.6 seconds** (and several seconds at 10,000 posts).

[Gemini 4 Neon](https://blog.google/innovation-and-ai/models-and-research/gemini-models/introducing-gemini-4-neon/) was remarkably sharp here: rather than reaching for an approximate nearest-neighbor heuristic that might subtly change cluster boundaries, it replaced the brute-force loop with an **exact** implementation that produces bit-for-bit identical Euclidean DBSCAN clusters in **19 to 28 ms** at 4,000 posts (and **62 to 85 ms** at 10,000 posts).

| Dataset | Apache Commons Math | Optimized Exact DBSCAN | Speedup |
| --- | ---: | ---: | ---: |
| 4,000 posts × 128 dim (15 clusters, exact parity verified) | ~1,100–1,600 ms | **~19–28 ms** | **~50–60×** |
| 10,000 posts × 128 dim (stress test) | multi-second | **~62–85 ms** | n/a |

<details>
<summary><strong>Expand the math and engineering behind the clustering speedup (Cauchy–Schwarz pruning, dot-product shortcut, and isotropic mean-centering)</strong></summary>

### 1. Exact Cauchy–Schwarz Multi-Axis Pruning

For any unit vector $u$ ($\|u\|_2 = 1$), the Cauchy–Schwarz inequality guarantees:

$$|x_i \cdot u - x_j \cdot u| = |(x_i - x_j) \cdot u| \le \|x_i - x_j\|_2$$

In plain terms: if two posts are farther apart than $\varepsilon$ along **any** single 1D unit direction $u$, their true distance in 256-dimensional space is guaranteed to be greater than $\varepsilon$.
You can reject the pair in $O(1)$ without ever touching the full 256-float vectors.

To make this pruning as tight as possible, the clusterer:
1. Subsamples ~1,024 posts and runs a few steps of deflated power iteration to approximate the **top 8 principal components** (the directions along which different topics spread farthest apart), then appends **4 orthogonal random unit vectors** for 12 orthonormal projection axes in total. Even approximate PCA directions only need unit length for Cauchy–Schwarz to stay 100% exact (zero false negatives).
2. Projects all $N$ posts onto those 12 axes and **sorts all posts along the primary axis**.
3. Scans only the upper triangle ($j > i$) in parallel across CPU cores, and **breaks out of the inner loop immediately** as soon as the 1D gap along the primary axis exceeds $\varepsilon$.
4. Checks the remaining 11 scalar projections before ever loading the full embedding vectors for the few surviving candidates.

### 2. Unit-Vector Dot-Product Shortcut (Zero Square Roots)

Because the embeddings are L2-normalized ($\|u\|_2 = \|v\|_2 = 1$), squared Euclidean distance simplifies directly to a dot product:

$$\|u - v\|_2^2 = \|u\|_2^2 + \|v\|_2^2 - 2(u \cdot v) = 2 - 2(u \cdot v)$$

So the DBSCAN neighborhood check becomes:

$$\|u - v\|_2 \le \varepsilon \iff u \cdot v \ge 1 - \frac{\varepsilon^2}{2}$$

No per-dimension subtraction, no square roots.
Everything runs on a single contiguous flat `float[]` array physically reordered in sorted axis order (for sequential L1/L2 CPU cache prefetching) with 4-way unrolled loops so HotSpot C2 auto-vectorizes the dot products into SIMD instructions.
Only pairs that land inside a tiny $\pm 10^{-4}$ floating-point rounding band near the threshold fall back to double precision, preserving exact mathematical parity.
Finally, the cluster expansion itself uses flat primitive arrays with zero object boxing.

### 3. Fixing Topic Collapse with Isotropic Mean-Centering

Speed alone was not enough.
On live Bluesky streams, `gemini-embedding-001` exhibited a classic Transformer geometry quirk known as [**embedding anisotropy**](https://www.emergentmind.com/topics/anisotropy-in-embedding-representations): posts written in the same language share a strong common background direction, packing unrelated topics into a narrow cone on the unit hypersphere.
Generic short posts sit near the middle of that cone and act as bridges, causing DBSCAN to merge 90%+ of posts into a single catch-all bubble.

The fix ("All-but-the-Top" isotropic mean-centering) is three lines of linear algebra applied right before clustering: L2-normalize every vector, compute the rolling window's mean vector $\mu$, subtract $\mu$ from every vector, and re-normalize to unit length:

$$\tilde{v}_i = \frac{\hat{v}_i - \mu}{\|\hat{v}_i - \mu\|_2}$$

Removing that shared mean spreads unrelated conversations cleanly across the entire unit sphere, turning one giant blob into distinct, balanced topic clusters.

</details>

## Try It Out

The app is running live on Cloud Run, and the full source code (including offline benchmarks and exact DBSCAN parity tests you can run without an API key) is on GitHub:

- **Live English trends:** [bsky-topics.cloud.run/?lang=en](https://bsky-topics.cloud.run/?lang=en)
- **Live French trends:** [bsky-topics.cloud.run/?lang=fr](https://bsky-topics.cloud.run/?lang=fr)
- **GitHub repository:** [github.com/glaforge/bluesky-topic-analysis](https://github.com/glaforge/bluesky-topic-analysis)

Between `gemini-decision-1` cleaning and routing the firehose for pennies, Gemini 4 Neon turning a multi-second clustering bottleneck into a ~20 ms exact pass via `/boost`, and `/swarm` accelerating the multi-view frontend and Cloud Run setup, reviving an old side project has never been this fun.
Feel free to poke around the live views (especially **Cross-Lang Bridges** and **Semantic Galaxy**) and let me know what you think on Bluesky at [@glaforge.dev](https://bsky.app/profile/glaforge.dev)!

