Building Resilient ETL Pipelines Using SOLID
Applying SOLID design principles to data pipelines — building for efficiency, flexibility, and future growth.
The Aqueduct of Segovia
In the realm of software engineering, continuous learning and adaptation are the keys to personal and professional growth. My recent endeavor on this path led me to delve into the profound insights shared by Uncle Bob in his book Clean Architecture. The more I read, the more I was drawn towards the essence of SOLID principles which form the bedrock of crafting maintainable and scalable software systems.
Inspired by the Feynman Learning Technique, which emphasizes learning by teaching, I decided to embark on a journey to not only apply these principles but also share the knowledge with the community. This technique suggests that if you can't explain something in simple terms, you don't understand it. And what better way to do this than by writing code?
Being a data engineer, my day-to-day tasks often revolve around Extract, Transform, Load (ETL) processes which are crucial for the data lifecycle in any organization. I realized that building an ETL process from scratch would be an ideal project to apply and demonstrate the SOLID principles.
The source code can be found in this repo.
Implementing SOLID Principles in ETL Pipelines
1. Single Responsibility Principle (SRP)
The Single Responsibility Principle (SRP) posits that a class should have only one reason to change, ensuring that each class encapsulates a single aspect of the system. In our ETL pipeline, this principle is well-illustrated through the separation of concerns among different modules.
# Connector Module
class AbstractConnector(ABC):
@abstractmethod
def connect(self):
pass
# Extractor Module
class AbstractExtractor(ABC):
@abstractmethod
def extract(self):
pass
# Transformer Module
class AbstractTransform(ABC):
def __init__(self, data):
self.data = data
@abstractmethod
def transform(self):
pass
# Loader Module
class AbstractLoader(ABC):
@abstractmethod
def load(self, data):
pass- Connector Module: encapsulates the logic for connecting to a data source. Any change related to how connections are established or managed will only affect this module.
- Extractor Module: encapsulates the logic for extracting data from a source.
- Transformer Module: encapsulates the logic for transforming data.
- Loader Module: encapsulates the logic for loading data into a destination.
Each module has only one reason to change, adhering to SRP.
2. Open-Closed Principle (OCP)
The Open-Closed Principle posits that software entities should be open for extension but closed for modification. In our ETL pipeline, this principle is illustrated through the design of abstract classes and their extensions.
class AbstractExtractor(ABC):
@abstractmethod
def extract(self):
pass
class PostgresExtractor(AbstractExtractor):
def __init__(self, connection_details, query):
self.connector = PostgreSQLConnector(**connection_details)
self.query = query
def extract(self):
try:
self.connector.connect()
with self.connector.connection.cursor() as cur:
cur.execute(self.query)
result = cur.fetchall()
column_names = [col[0] for col in cur.description]
return column_names, result
finally:
self.connector.close()
def etl_process(extractor: AbstractExtractor):
column_names, data = extractor.extract()By adhering to OCP, our ETL process accommodates new data sources seamlessly. For instance, if a new data source like a CSV file is introduced, you can extend the AbstractExtractor class without modifying existing code:
class CSVExtractor(AbstractExtractor):
def __init__(self, file_path):
self.file_path = file_path
def extract(self):
data = []
with open(self.file_path, newline='', encoding='utf-8') as csvfile:
csvreader = csv.reader(csvfile)
for row in csvreader:
data.append(row)
column_names = data[0]
data = data[1:]
return column_names, dataThe etl_process function can now work with any extractor that extends AbstractExtractor.
3. Liskov Substitution Principle (LSP)
Derived classes should be substitutable for their base classes without altering the correctness of the program. CursorToPandasTransformer is a derived class of AbstractTransform and can be substituted without causing issues.
class AbstractTransform(ABC):
def __init__(self, data):
self.data = data
@abstractmethod
def transform(self):
pass
class CursorToPandasTransformer(AbstractTransform):
def __init__(self, data):
super().__init__(data)
def transform(self):
df = pd.DataFrame(self.data[1], columns=self.data[0])
return df
def etl_process(transformer: AbstractTransform):
transformed_data = transformer(data).transform()4. Interface Segregation Principle (ISP)
Clients should not be forced to depend on interfaces they do not use. In the ETL pipeline, each component has its own minimal interface.
class AbstractLoader(ABC):
@abstractmethod
def load(self, data):
pass
class PandasToCSVLoader(AbstractLoader):
def __init__(self, file_name):
self.file_name = file_name
def load(self, data):
data.to_csv(self.file_name)
class PandasToSQLiteLoader(AbstractLoader):
def __init__(self, connector, table_name):
self.connector = connector
self.table_name = table_name
def load(self, data):
try:
self.connector.connect()
data.to_sql(self.table_name, self.connector.connection, if_exists='replace', index=False)
except Exception as e:
logger("Error loading data into SQLite:", e)
finally:
self.connector.close()Each loader has its own specific implementation without being burdened by methods or properties they don't require.
5. Dependency Inversion Principle (DIP)
High-level modules should not depend on low-level modules; both should depend on abstractions. Our high-level ETL class depends on abstractions of the extractor, transformer, and loader, rather than on their concrete implementations.
class ETL:
def __init__(self, config):
self.config = config
self.extractor = self._get_instance(extractor, self.config.extractor_type, self.config.get_extractor_config())
self.transformers = [self._get_instance(transform, t) for t in self.config.get_transformer_configs()]
self.loader = self._get_instance(load, self.config.loader_type, self.config.get_loader_config())
def _get_instance(self, module, class_name, config=None):
cls = self.config.get_class_reference(module, class_name)
if config:
return cls(**config)
else:
return cls
def process(self):
data = self.extractor.extract()
for transformer in self.transformers:
data = transformer(data).transform()
self.loader.load(data)
logger("ETL process completed successfully!")Putting it all together:
from src.config import Config
from src.etl import ETL
config = Config(
extractor_type="PostgresExtractor",
loader_type="PandasToCSVLoader",
transformers=["CursorToPandasTransformer"],
extractor={
"connection_details": {
"host": "localhost",
"database": "world",
"user": "postgres",
"password": "postgres"
},
"query": "SELECT * FROM public.city limit 10"
},
loader={"file_name": "output.csv"}
)
etl_process = ETL(config)
etl_process.process()Conclusion
By adhering to the SOLID principles, we can build an ETL pipeline that is robust, maintainable, and easy to extend. As we continue to grow and adapt our pipeline to meet new challenges, these principles will serve as a guiding light, ensuring that our software remains high-quality and our development process efficient.
If you're eager to dive deeper, visit the GitHub repository.