DEV Community

Cover image for Building a Real-Time Earthquake Alert System Using BOT, API & Database
Naimur Rahman Nahid
Naimur Rahman Nahid

Posted on

Building a Real-Time Earthquake Alert System Using BOT, API & Database

Naimur Rahman Nahid Android Earthquake Apps Idea

The global earthquake monitoring ecosystem provides public APIs for developers to consume real-time seismic activity data. Services like USGS, IRIS, and EMSC offer free feeds, but they also enforce rate limits. If your application has thousands of active users, directly calling these external APIs from each device is not scalable.

Instead, a more reliable strategy is to create a background BOT + local database + server API architecture.

Your server fetches earthquake data periodically, stores it locally, and your mobile/web users read everything from your backend — not from external APIs.

This guide walks you through building a real-time Earthquake Alert System using external feeds, a BOT worker, and a fast backend.


Prerequisites

Before starting, you should be familiar with:

  • Basic backend development (Node, PHP, Python)
  • REST APIs & JSON parsing
  • SQL databases (PostgreSQL/MySQL)
  • Basic mobile or web app development concepts

Your development environment should include:

  • Node.js v16 or higher
  • PostgreSQL/MySQL database
  • A local or cloud server
  • API testing tools (Postman/Insomnia)

Step 1: Choose an Earthquake Data Source

Reliable free sources:

Recommended Feed (USGS GeoJSON):

https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geo.json

You get:

  • Magnitude
  • Location (place)
  • Depth
  • Time
  • Coordinates
  • Event ID
  • Tsunami flag
  • Metadata

Step 2: Set Up Your Project Structure

Example folder layout:

earthquake-alert/
├─ src/
│ ├─ bot/
│ │ └─ fetch.js
│ ├─ api/
│ │ └─ earthquakes.js
│ └─ server.js
├─ package.json
├─ .env


Step 3: Create the Earthquake Database Table

Using PostgreSQL:

CREATE TABLE earthquakes (
id SERIAL PRIMARY KEY,
external_id VARCHAR(100) UNIQUE,
magnitude NUMERIC(4,2),
depth NUMERIC(6,2),
place TEXT,
time_utc TIMESTAMP,
latitude NUMERIC(9,6),
longitude NUMERIC(9,6),
url TEXT,
source VARCHAR(20),
created_at TIMESTAMP DEFAULT NOW()
);

Indexes:

CREATE INDEX idx_quake_time ON earthquakes(time_utc DESC);
CREATE INDEX idx_quake_mag ON earthquakes(magnitude DESC);


Step 4: Build the BOT to Fetch Earthquake Data

Create file: src/bot/fetch.js

import fetch from "node-fetch";
import { Pool } from "pg";

const pool = new Pool({ connectionString: process.env.DATABASE_URL });

const API_URL =
 "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson";

export async function fetchEarthquakes() {
  const res = await fetch(API_URL);
  const json = await res.json();

  const client = await pool.connect();

  try {
    await client.query("BEGIN");

    for (const item of json.features) {
      const p = item.properties;
      const g = item.geometry;

      await client.query(
        `INSERT INTO earthquakes 
         (external_id, magnitude, depth, place, time_utc, latitude, longitude, url, source)
         VALUES ($1, $2, $3, $4, to_timestamp($5/1000), $6, $7, $8, 'USGS')
         ON CONFLICT (external_id) DO NOTHING`,
        [
          item.id,
          p.mag,
          g.coordinates[2],
          p.place,
          p.time,
          g.coordinates[1],
          g.coordinates[0],
          p.url
        ]
      );
    }

    await client.query("COMMIT");
  } catch (error) {
    await client.query("ROLLBACK");
  } finally {
    client.release();
  }
}
Run BOT every 30 seconds:
Enter fullscreen mode Exit fullscreen mode

setInterval(fetchEarthquakes, 30000);
fetchEarthquakes();

Step 5: Create a Backend API for Your App

Inside src/api/earthquakes.js:

Enter fullscreen mode Exit fullscreen mode

app.get("/api/earthquakes/recent", async (req, res) => {
const minutes = req.query.minutes || 60;

const result = await pool.query(
SELECT * FROM earthquakes
WHERE time_utc >= NOW() - ($1 || ' minutes')::interval
ORDER BY time_utc DESC
,
[minutes]
);

res.json(result.rows);
});

Clients fetch from your backend only — no rate limits.

---

Step 6: Add Real-Time Alerts (Socket.io)

Server emit:

Enter fullscreen mode Exit fullscreen mode

io.emit("earthquake-alert", {
magnitude,
latitude,
longitude,
place
});


Client receive:

Enter fullscreen mode Exit fullscreen mode

socket.on("earthquake-alert", (data) => {
// Show notification
// Play siren sound
});

Step 7: Notification Logic (Mobile/Web)

Simple example:

Enter fullscreen mode Exit fullscreen mode

if (distance <= 300 && magnitude >= 4.5) {
triggerSiren();
showNotification();
}



Only relevant earthquakes trigger alerts.

-------

Step 8: Test, Deploy & Scale

Checklist:

- BOT updates data successfully
- API returns latest earthquakes
- Filters work (time, magnitude, region)
- Mobile/web client connects
- Push notifications triggered correctly
Deploy BOT + Backend on any server:

- VPS (DigitalOcean / Linode)
- Render
- Railway
- AWS / GCP


By using a BOT-driven architecture, you can:

1. Avoid API rate limits
2. Support unlimited users
3. Improve performance
4. Deliver fast, real-time alerts

This architecture works for mobile apps, dashboards, emergency systems, or public alert applications.

More From Me

[Blog Website:](https://www.nijerinfo-bd.com/)

Web Development Agency: [Naimur Rahman Nahid](https://naimurrahmannahid.com/)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)