Examples & Use Cases

Real-world implementations of StackSleuth across different technologies

React E-commerce Performance

React

Monitor performance in a React e-commerce application with dynamic product listings and checkout flow.

Setup

// app.js
import { ReactAgent } from '@stacksleuth/react-agent';

ReactAgent.init({
  apiKey: process.env.REACT_APP_STACKSLEUTH_KEY,
  trackRenders: true,
  trackStateChanges: true,
  componentWhitelist: ['ProductList', 'CartDrawer', 'CheckoutForm']
});

Product List Component

import { useProfiler } from '@stacksleuth/react-agent';

function ProductList({ category }) {
  const profiler = useProfiler('ProductList');
  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchProducts = async () => {
      profiler.startMeasure('fetch-products');
      try {
        const response = await api.getProducts(category);
        setProducts(response.data);
      } finally {
        profiler.endMeasure('fetch-products');
        setLoading(false);
      }
    };
    
    fetchProducts();
  }, [category]);

  return (
    <div className="product-grid">
      {loading ? (
        <LoadingSpinner />
      ) : (
        products.map(product => (
          <ProductCard key={product.id} product={product} />
        ))
      )}
    </div>
  );
}

Captured Metrics

  • Component render time: 12ms
  • API fetch duration: 245ms
  • Re-renders on category change: 3
  • Memory usage: 4.2MB

Vue Admin Dashboard

Vue

Track performance in a Vue.js admin dashboard with real-time data updates and complex state management.

Main Setup

// main.js
import { createApp } from 'vue';
import { VueAgent } from '@stacksleuth/vue-agent';

const app = createApp(App);

app.use(VueAgent, {
  apiKey: process.env.VUE_APP_STACKSLEUTH_KEY,
  trackComponents: true,
  trackVuexMutations: true,
  slowComponentThreshold: 50
});

Dashboard Component

<template>
  <div class="dashboard">
    <MetricsGrid :metrics="metrics" />
    <RealtimeChart :data="chartData" />
    <DataTable :items="tableData" />
  </div>
</template>

<script>
import { useStackSleuth } from '@stacksleuth/vue-agent';

export default {
  setup() {
    const { trackMethod } = useStackSleuth();
    
    const loadDashboardData = trackMethod('loadDashboardData', async () => {
      const [metrics, chart, table] = await Promise.all([
        api.getMetrics(),
        api.getChartData(),
        api.getTableData()
      ]);
      
      return { metrics, chart, table };
    });
    
    onMounted(() => {
      loadDashboardData();
    });
  }
}
</script>

Node.js Microservice

Node.js

Monitor Express.js microservice performance with route tracking and middleware profiling.

Express Setup

const express = require('express');
const { BackendAgent } = require('@stacksleuth/backend-agent');

const app = express();
const agent = new BackendAgent({
  apiKey: process.env.STACKSLEUTH_KEY,
  serviceName: 'user-service'
});

// Apply middleware
app.use(agent.middleware());

// Track specific routes
app.get('/api/users/:id', agent.trackRoute(), async (req, res) => {
  const user = await db.users.findById(req.params.id);
  res.json(user);
});

// Custom metrics
app.post('/api/users', async (req, res) => {
  const timer = agent.startTimer('user.creation');
  try {
    const user = await createUser(req.body);
    agent.recordMetric('user.created', 1);
    res.json(user);
  } finally {
    timer.end();
  }
});

Redis Caching Layer

Redis

Implement performance monitoring for a Redis caching layer with hit/miss tracking.

Cache Implementation

import { RedisAgent } from '@stacksleuth/redis-agent';
import { createClient } from 'redis';

class CacheService {
  constructor() {
    this.client = createClient();
    this.agent = new RedisAgent({ apiKey: process.env.STACKSLEUTH_KEY });
    this.agent.instrument(this.client);
  }

  async get(key) {
    const value = await this.client.get(key);
    
    // Track cache hit/miss
    this.agent.recordMetric(value ? 'cache.hit' : 'cache.miss', 1);
    
    return value;
  }

  async set(key, value, ttl = 3600) {
    const timer = this.agent.startTimer('cache.write');
    try {
      await this.client.setex(key, ttl, JSON.stringify(value));
    } finally {
      timer.end();
    }
  }
  
  async invalidate(pattern) {
    const timer = this.agent.startTimer('cache.invalidation');
    const keys = await this.client.keys(pattern);
    if (keys.length > 0) {
      await this.client.del(...keys);
    }
    timer.end({ keysDeleted: keys.length });
  }
}

Performance Insights

  • Average cache hit rate: 87%
  • Cache write latency: 2.3ms
  • Peak operations/sec: 12,450
  • Memory usage: 245MB

Full Stack SaaS Application

Full Stack

Complete monitoring setup for a SaaS application with React frontend, Node.js backend, and PostgreSQL database.

Frontend (React)

// Frontend monitoring setup
import { ReactAgent } from '@stacksleuth/react-agent';
import { FrontendAgent } from '@stacksleuth/frontend-agent';

// Initialize agents
ReactAgent.init({
  apiKey: process.env.REACT_APP_STACKSLEUTH_KEY,
  trackRenders: true
});

FrontendAgent.init({
  apiKey: process.env.REACT_APP_STACKSLEUTH_KEY,
  trackPageLoads: true,
  trackApiCalls: true,
  trackErrors: true
});

Backend (Node.js + Express)

// Backend monitoring setup
const { BackendAgent } = require('@stacksleuth/backend-agent');
const { DatabaseAgent } = require('@stacksleuth/db-agent');

const agent = new BackendAgent({
  apiKey: process.env.STACKSLEUTH_KEY,
  serviceName: 'saas-api'
});

// Database monitoring
const dbAgent = new DatabaseAgent({
  apiKey: process.env.STACKSLEUTH_KEY,
  slowQueryThreshold: 100
});

// Apply to PostgreSQL
dbAgent.instrumentPostgres(pgPool);

Deployment Configuration

# docker-compose.yml
version: '3.8'
services:
  frontend:
    build: ./frontend
    environment:
      - REACT_APP_STACKSLEUTH_KEY=${STACKSLEUTH_KEY}
    
  backend:
    build: ./backend
    environment:
      - STACKSLEUTH_KEY=${STACKSLEUTH_KEY}
      - NODE_ENV=production
    
  postgres:
    image: postgres:14
    environment:
      - POSTGRES_DB=saas_db

Monitoring Architecture

Full Stack Monitoring Architecture

E2E Testing & Monitoring

Browser

Automated browser testing with performance monitoring for critical user journeys.

User Journey Testing

import { BrowserAgent } from '@stacksleuth/browser-agent';

const agent = new BrowserAgent({
  apiKey: process.env.STACKSLEUTH_KEY,
  headless: true,
  recordVideo: true
});

describe('User Registration Flow', () => {
  it('should complete registration within 5 seconds', async () => {
    const session = await agent.startSession({
      name: 'user-registration',
      viewport: { width: 1280, height: 720 }
    });
    
    // Navigate to registration page
    await session.goto('https://app.example.com/register');
    
    // Fill registration form
    await session.fill('#email', 'test@example.com');
    await session.fill('#password', 'SecurePass123!');
    await session.fill('#confirmPassword', 'SecurePass123!');
    
    // Submit and wait for redirect
    const metrics = await session.measureAction('registration', async () => {
      await session.click('button[type="submit"]');
      await session.waitForURL('**/dashboard');
    });
    
    expect(metrics.duration).toBeLessThan(5000);
    await session.end();
  });
});

Integration Patterns

Microservices

Distributed tracing across multiple services with correlation IDs and request tracking.

View Pattern →

Mobile + API

Monitor mobile app performance alongside API endpoints for complete user journey tracking.

View Pattern →

Real-time Analytics

Stream performance data to analytics platforms for custom dashboards and alerts.

View Pattern →

Serverless

Monitor AWS Lambda, Vercel, and other serverless platforms with automatic cold start detection.

View Pattern →