Skip to content
Being BE
Go back

Query Optimization, Part 1: Choosing APIs and Measuring a Performance Baseline

—viewsEdit page
On this page

This time, I planned to improve an existing project to strengthen my portfolio and experience the process of query analysis and optimization.
I chose Wihada, a project I had worked on before (a service that manages consultation, ordering, and payment for custom cake shops in one workflow).\

GitHub Repository
Wihada API
kmsdevdata-sketch/wihada-api

A backend service that manages consultation, ordering, and payment for custom cake shops in one workflow

View on GitHub
Wihada API GitHub repository preview
Query optimization series

The testing and improvements in this post were carried out against the local application, not the deployed environment!

Choosing the APIs to analyze

First, I needed to select the APIs to test and improve, so I looked for candidates using the criteria below.

  • Identify the main APIs that read from the database.
  • → Classify candidates by read frequency, query complexity, and the possibility of data growth.
  • → Select two or three target APIs from those candidates. Wihada handles buyer, seller, and administrator APIs in the same application. For the initial classification, I focused on the seller APIs because I thought they would manage relatively more data.

I used Codex to identify and classify the APIs, and the list below was the result.

AreaAPIs
Dashboard aggregatesGET /seller/dashboard, GET /seller/dashboard/revenue, GET /seller/dashboard/revenue/transactions
Order list and calendarGET /seller/orders, GET /seller/orders/calendar/today, GET /seller/orders/calendar/week, GET /seller/orders/calendar/month
Inquiry and chat listsGET /seller/inquiries, GET /seller/inquiries/{inquiryId}/events
Inquiry historyGET /seller/inquiries/{inquiryId}/order-form-submissions, GET /seller/inquiries/{inquiryId}/confirmations
Overall store statusGET /seller/store/management-status
Various settings and notice managementGET /seller/store/settings, PUT /seller/store/settings, GET /seller/notices, PUT /seller/notices
Image and gallery listsGET /seller/gallery-items, GET /seller/representative-images

At this point, I excluded single-item APIs and first narrowed the list to items, such as list and aggregate APIs, whose query costs could rise as the number of records retrieved increased.

As for read frequency, there was no real user data, so I could only guess. I therefore removed it from the selection criteria and chose items based on code whose cost would grow with the data and where repeated reads occurred.

  1. GET /seller/inquiries: loads all inquiries for a store and separately queries the number of unread items for each inquiry.
  2. GET /seller/dashboard: queries several aggregates and the number of unread items for each inquiry.
  3. GET /seller/orders: loads the entire accumulated order list.

Setting up a local test environment

Test environment

For the local test environment, I ran the Spring Boot application locally with the local-scenario profile and configured it to connect to PostgreSQL at localhost:5432. The application originally used Cognito for authentication, but I used a local test token for the local tests, and the local file system instead of S3 for storing assets.

Preparing test data

StageInquiries per storeEvents per inquiryOrders per store
Data volume1,000101,000

Test data insertion result Buyers: 1,000
Chat rooms: 1,000
Chat messages: 10,000
Chat timeline events (e.g., issuing order forms, requesting payments, etc.): 10,000
Orders: 1,000

Measuring the baseline

Test tool

I used k6 as the test tool. The biggest reason I chose k6 was that I had used it before, and I came to use it often because the process from installation to writing the code and running it was simpler than with other tools.

Test scenario

Goal

The goal of this test was to get baseline values for how long each API takes with the current data and how that changes as the number of requests increases, rather than to find out “the maximum number of users who can connect” or “how much load it can withstand.” (I would optimize the queries, measure again, and compare the results.)

Request rate

StageRequest rateDurationPurpose
Warm-upLow30–60 secondsReduce first-run effects
Stage 11 request/second2 minutesBaseline response time
Stage 23 requests/second2 minutesEffect of increased traffic
Stage 35 requests/second2 minutesEffect of another increase

Reason for warming up: the first few requests can be affected by the JVM’s running state, database connection preparation, and disk caching, so warming up lets me distinguish those effects when measuring.

Expected results and metrics

MetricWhat I wanted to check
SQL executions per requestDoes an inquiry or dashboard request repeat a query for every inquiry?
Execution time per SQL and total database timeWhich queries consume the most time?
API response time, p50 and p95How much does database work affect the actual response time?
Returned item count and response sizeAm I comparing responses with the same amount of data?
Error rateDo requests fail as the system slows down?
Actual request count and dropped_iterationsDid the planned traffic actually reach the application?

Test code

import http from 'k6/http';
import { check } from 'k6';

// APIs under test
const paths = {
    inquiries: '/seller/inquiries',
    dashboard: '/seller/dashboard',
    orders: '/seller/orders',
};

// Values supplied at runtime
const target = __ENV.TARGET;
const rate = Number(__ENV.RATE);
const minItems = Number(__ENV.MIN_ITEMS || 1000);
const baseUrl = __ENV.BASE_URL || 'http://localhost:8080';
const token = __ENV.SELLER_TOKEN || 'local-seller-token';

export const options = {
    scenarios: {
        seller_query: {
            executor: 'constant-arrival-rate',
            rate,
            timeUnit: '1s',
            duration: __ENV.DURATION || '2m',
            preAllocatedVUs: 20,
            maxVUs: 100,
        },
    },
    thresholds: {
        checks: ['rate==1'],
    },
};

export default function () {
    const response = http.get(`${baseUrl}${paths[target]}`, {
        headers: {
            Authorization: `Bearer ${token}`,
        },
    });

    let body = null;
    if (response.status === 200) {
        try {
            body = response.json();
        } catch (_) {
            // A non-JSON response fails the validation below
        }
    }

    const validData =
        body !== null &&
        body.success === true &&
        (target === 'dashboard'
            ? body.data !== null &&
            typeof body.data === 'object' &&
            !Array.isArray(body.data)
            : Array.isArray(body.data) && body.data.length >= minItems);

    check(response, {
        'HTTP 200': (r) => r.status === 200,
        'expected response data': () => validData,
    });
}

Results

Chat room lookup summary

Metric1 request/second3 requests/second5 requests/second
Actual requests120361601
Mean response time302.90ms255.51ms267.35ms
p50 response time299.22ms241.77ms244.66ms
p95 response time336.84ms328.44ms384.94ms
Maximum response time527.22ms491.86ms1.04s
HTTP failures000
Response checksAll passedAll passedAll passed
Data received93MB280MB467MB

Dashboard summary

Metric1 request/second3 requests/second5 requests/second
Actual requests120361601
Mean response time275.00ms226.00ms223.36ms
p50 response time269.80ms218.27ms212.23ms
p95 response time322.66ms271.25ms289.64ms
Maximum response time379.30ms572.89ms588.90ms
HTTP failures000
Response checksAll passedAll passedAll passed
Data received1.4MB4.3MB7.1MB

Order list summary

Metric1 request/second3 requests/second5 requests/second
Actual requests121361600
Mean response time37.04ms31.52ms31.79ms
p50 response time37.90ms31.31ms32.38ms
p95 response time45.19ms41.84ms41.41ms
Maximum response time51.07ms117.52ms78.19ms
HTTP failures000
Response checksAll passedAll passedAll passed
Data received71MB213MB353MB

I decided there was no reason to run additional tests for these API tests.


Edit page

Next Post
Query Optimization, Part 2: Analyzing SQL and Execution Plans

Comments

Use your GitHub account to comment or react.