To efficiently store and manage frequently fetched data such as open orders, trade history, holdings, reports, and favorite symbols for each user in a scalable and high-performance manner, you can follow these best practices:
Design your database schema to optimize for read performance while ensuring data integrity. Here’s a suggested schema for the tables you mentioned:
CREATE TABLE users (
id SERIAL PRIMARY KEY,
username VARCHAR(50) UNIQUE NOT NULL,
password_hash VARCHAR(255) NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE open_orders (
id SERIAL PRIMARY KEY,
user_id INT REFERENCES users(id),
symbol VARCHAR(10) NOT NULL,
order_type VARCHAR(10) NOT NULL, -- 'limit' or 'market'
quantity INT NOT NULL,
price DECIMAL(10, 2),
status VARCHAR(20) DEFAULT 'open',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
CREATE TABLE trade_history (
id SERIAL PRIMARY KEY,
user_id INT REFERENCES users(id),
symbol VARCHAR(10) NOT NULL,
trade_type VARCHAR(10) NOT NULL, -- 'buy' or 'sell'
quantity INT NOT NULL,
price DECIMAL(10, 2) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE holdings (
id SERIAL PRIMARY KEY,
user_id INT REFERENCES users(id),
symbol VARCHAR(10) NOT NULL,
quantity INT NOT NULL,
average_price DECIMAL(10, 2) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
CREATE TABLE favorite_symbols (
id SERIAL PRIMARY KEY,
user_id INT REFERENCES users(id),
symbol VARCHAR(10) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
To improve query performance, especially for frequent fetches, create indexes on columns that are often queried:
CREATE INDEX idx_user_id ON open_orders(user_id);
CREATE INDEX idx_user_id ON trade_history(user_id);
CREATE INDEX idx_user_id ON holdings(user_id);
CREATE INDEX idx_user_id ON favorite_symbols(user_id);
Implement caching to reduce the load on your database and speed up data retrieval: